Hi,
I’m learning C++ and I’m in a bit of a rut here. Could anyone help me out?
First of all I can’t fully grasp what is going on in this section of code. The code is to find the biggest element in an array.
#include <iostream.h>
main()
{
int biggest( int item_array[], int n_elements );
int item_array[5] = { 1, 2, 35, 3, 4 }; //An array
cout << "The biggest element is " << biggest(item_array, 5) << "
";
return(0);
}
int &biggest( int array[], int n_elements )
{
int index; //Current index
int biggest; //Index of the biggest element in the array
//Assume the first is the biggest
biggest = 0;
for( index = 1; index < n_elements; ++index )
{
if(array[biggest] < array[index])
biggest = index;
}
return(array[biggest]);
}
Is the variable biggest [ int biggest; //Index of the biggest element in the array ] a reference to the function biggest [ int
&biggest( int array[], int n_elements ) ]?
Starting with the function we make the function biggest a reference. We then declare the parameters array[] and n_elements.
Maybe my problem is that I don’t fully understand the references. How exactly does the reference work?
We then create the variables index and biggest - that I understand.
We then state that
biggest = 0;
being the biggest element in the array currently known.
Then we create the loop, stating that while index = 1 and index < number of elements in the array the index must be incremented.
Then to determine whether biggest is still the largest element in the array, or not, we use an if statement:
if(array[biggest] < array[index])
If it is smaller, then we must change it’s value accordinly:
biggest = index;
We then return the value of our function.
return(array[biggest]);
Then we want to print out the biggest element in the array, so we define the function prototype:
int biggest( int item_array[], n_elements );
We then define the array, item_array:
int item_array[5] = { 1, 2, 35, 3, 4 };
Then we print the biggest element in the array:
cout << "The biggest element is " << biggest(item_array, 5) << "
";
The problem is that when I run the program (after compilation) it returns the result:
The biggest element is 37879624
Shouldn't it be 35?
I would really appreciate any help. Cheers


