Finding Min and Max, output number that not assign?

I have 2 codes that display the min and max. the first code didnt understand why it output 1 for the min, where is the compiler getting one. the second code, i just switch the variable assignment and it works fine any theory why it displayed one?

Unsolve Errorreasoning

# include <iostream>
using namespace std;

int main(){

int grade[5];
int total=0;



for(int a=0; a<5; a++){

cin>>grade[a];
total+=grade[a];
}
int min=grade[0];
int max=grade[0];

for(int b=1; b<5; b++){
if (grade[b]<min)
min=grade[b];

if (grade[b]>max)
max=grade[b];
}
cout<<min<<endl<<max;
return 0;
}

/*12
13
14
15
16
1
16
--------------------------------
Process exited after 3.196 seconds with return value 0
Press any key to continue . . .
*/


Ok this one work fine

# include <iostream>
using namespace std;

int main(){

int grade[5];
int total=0;



for(int a=0; a<5; a++){

cin>>grade[a];
total+=grade[a];
}
int min=grade[0];
int max=grade[0];

for(int b=1; b<5; b++){
if (grade[b]<min)
min=grade[b];

if (grade[b]>max)
max=grade[b];
}
cout<<min<<endl<<max;
return 0;
}

/*
12
13
14
15
16
12
16
--------------------------------
Process exited after 3.719 seconds with return value 0
Press any key to continue . . .*/
i just switch the variable assignment
What do you mean? Both codes are identical.
The assignment of

int min=grade[0];
int max=grade[0];

i only move after the first for loop, and that work fine
if that assignment happened before the first loop grade[0] is uninitialzed. Then it may contain 1 or any other arbitrary number.
Topic archived. No new replies allowed.