Hello I am trying to find the largest double in a array with a for loop; However, the for loop is not looping. It does get the double and sizeOfArray is right, but it won't loop for any reason.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
double largestArray(double* array, int sizeOfArray);
int main()
{
double numbers[] = { 4.5, 3.4, 5.6, 9.1, 6.7, 7.8 };
int sizeOfArray = sizeof(numbers) / sizeof(numbers[0]); // = 6
cout << largestArray(numbers, sizeOfArray);
cin.get();
return 0;
}
double largestArray(double* array, int sizeOfArray) {
double maxNum = 0;
for (int i = 0; i < sizeOfArray; i++) { //Does not loop
if (array[i] > maxNum) maxNum = array[i];
return maxNum;
}
}
Line 17
After the if statement on the first iteration, it will return. Thus exiting the loop and the function. Move the return statement outside the loop and it should work.
1 2 3 4 5 6 7
double largestArray(double* array, int sizeOfArray) {
double maxNum = 0;
for (int i = 0; i < sizeOfArray; i++) { //Does not loop
if (array[i] > maxNum) maxNum = array[i];
}
return maxNum;
}