c++ - Use struct and recursion to find the largest number in an integer array -
i'm required use recursion find largest number in integer array. also, need both value , index of largest number. used "struct" gave me weird number , cannot figure out why.
here's struct:
struct maxnumber { int index; int value; }; here's find_largest function:
maxnumber numbers::find_largest() { maxnumber max; int current ;//keep track of current counter if(size == 1) { max.value = numarray[0]; max.index = 0; return max; } if(current < size && size != 0) //loop through numbers in array { if(numarray[current] >= max.value) { max.value = numarray[current]; max.index = current; } current++; find_largest(); } return max; } then, in main function, did this:
int result = num.find_largest().value; cout << "the largest number " << result << endl; however, gives me large number. need figure out what's wrong.
your main problem current has local storage , reallocated on every call findlargest. change declaration this
static int current = 0; and should work, if size , numarray defined elsewhere in class definition.
but same thing happening more subtly max, , should declared statically well.
Comments
Post a Comment