-
array help
Hi im reading a book and stuck in arrays
heres the fragment of code which i cant understand
Code:
for ( int student = 0; student < students; student++ )
{
cout << "Student " << setw( 2 ) << student + 1;
// output student's grades
for ( int test = 0; test < tests; test++ )
cout << setw( 8 ) << grades[ student ][ test ];
// call member function getAverage to calculate student's average;
// pass row of grades and the value of tests as the arguments
double average = getAverage( grades[ student ], tests );
cout << setw( 9 ) << setprecision( 2 ) << fixed << average << endl;
} // end outer for
} // end function
in the above code
average = getAverage (grades[student], tests);
grades is a ten by three 2D array
so passing student which is the first dimension or you may say it the row, will this pass all the colunms (the elements of second dimension array ? )
-
>> so passing student which is the first dimension or you may say it the row, will this pass all the colunms (the elements of second dimension array ? )
Yes, or more accurately, it passes the a pointer to the first element in the column you're interested in.
If we map out your array it might look like
Code:
STUDENTS
0 1 2
0 X X X
G 1 X X X
R 2 X X X
A 3 X X X
D 4 X X X
E 5 X X X
S 6 X X X
7 X X X
8 X X X
9 X X X
So if you pass the correct column and column size, then you get to use all their scores in the mean calculation. Imagine for instance that you passed
grades[1] to average(). That should be the same as a pointer to grades[1]'s first element: &grades[1][0].
Well, that's how I look at it; I think I rotated your matrix, but it looks to me like the simplest orientation. HTH.