Liam Liam - 24 days ago 6
C++ Question

Returning an int value from Find Max method & printing that in test file

Ive implemented a findMax method & a tester to test this function. Beforehand, I had the findMax method as void, and simply had cout << maxValue << at the end of the method, so that when it was called in the main tester, it printed out the result I wanted.

I'm trying to change that so the return type of the method is int, and in the main being able to print out the value being returned by the method. When i try manipulate the variable maxValue in the tester file, it says variable undefined.

What do I do to fix this? And also what is the most appropriate way to do this? having the method as a void type and having the cout statement within the method or having it as a integer type so that it returns an int at the end??

Thanks.

#ifndef FINDMAX_H
#define FINDMAX_H
#include <iostream>
using namespace std;

template < typename T >
int FindMax(T* array, int array_len) {

if (!array || array_len <=0 ) {
cout << "Invalid Array" << endl;
exit(1);
}

//T * newArray = new int[array_len]; //create new array
T maxValue = array[0]; //set to the first array element
int largestIndex = 0;

for (int i = 1; i < array_len; i++) { //going through array from pos 2
if (array[i] > maxValue) { //checking if value at array position i is > maxValue
maxValue = array[i]; //set maxValue = to element at current Array position
largestIndex = i; //set largest index = to the current index it is at
}

return maxValue;
}
//cout << "The max value in this array is: " << maxValue << endl;//return highest value in array

//cout << "The max value is at position : " << largestIndex << endl;//return position of highest value in the array
//cout << "" << endl;
}

#endif


Tester

#include "FindMax.h"
#include <iostream>
using namespace std;
#include <string>

int main() {


int array_len = 10;
int* array = new int[array_len];
double* array2 = new double[array_len];

for (int i = 0; i < array_len; i++) //fill array 1
array[i] = i * i;

for (int i = 0; i < array_len; i++) //fill array 2
array2[i] = i * 2.5;

FindMax(array, array_len);
cout << maxValue << endl; // error here


}

Answer

First of all the function has unreachable code

template < typename T >
int FindMax(T* array, int array_len) {
            //...

            return maxValue;
            return largestIndex;
           ^^^^^^^^^^^^^^^^^^^^^^
        }
        //cout << "The max value in this array is: " << maxValue << endl;//return highest value in array

        //cout << "The max value is at position : " << largestIndex << endl;//return position of highest value in the array
        //cout << "" << endl;
}

You should remove the last return statement.

As for the error then you should write

int maxValue = FindMax(array, array_len);
^^^^^^^^^^^^^
cout << maxValue << endl; // error here

that is you have to declare variable maxValue and assign it with the return value of the algorithm.