Reputation: 41
This is for my intro to C++ course. We are currently doing arrays and I'm trying to find the min value for each column of the array. here is what I have:
#include <iostream>
using namespace std;
int main(){
int grade[4][30] = {{76, 70, 80, 90, 100, 83, 61, 63, 64, 65, 97, 69, 70, 79,60, 70, 80, 90, 100, 83, 61, 63, 99, 98, 66, 69, 70, 79},
{74, 70, 80, 90,60, 61, 93, 88, 73, 65, 91, 69, 70, 79, 60, 70, 80, 90, 60, 83, 61, 63, 64, 65, 66, 69, 67, 74},
{72, 70, 80, 90, 99, 84, 62, 63, 99, 65, 66, 69, 70, 79, 60, 70, 80, 90, 99, 83, 61, 63, 64, 65, 66, 69, 70, 77},
{69, 70, 80, 90, 60, 61, 86, 63, 97, 97, 66, 69, 70, 79, 97, 70, 80, 90, 88, 83, 88, 63, 64, 65, 66, 69, 70, 79}};
int a;
for(int x = 0; x < 4; ++x){
a = grade[x][0];
for(int y = 0; y < 30; ++y){
if( a > grade[x][y])
a = grade[x][y];
cout << "a is " << a << " for the " << y << "time" << endl;}
cout << a << endl;}
return 0;
}
My problem is I don't understand why in the last two loops the value turns to 0? The real answer should be 60 for each row.
P.S I used this to find the maximum and it worked, but don't get why it won't work here?
Upvotes: 0
Views: 153
Reputation: 28685
for(int y = 0; y < 30; ++y){
It is because for example your first array contains only 28 explicitly initialized elements and you iterate till 30 (see above). The elements which you didn't initialize yourself are initialized to 0.
Upvotes: 4
Reputation: 72463
Your array initializers have less than 30 numbers. Since your array is declared to take 30 elements, the remaining entries are set to 0
.
Since you don't appear to have 0s in your data, you could use 0
as a sentinel to know to stop the loop.
Upvotes: 1