this is the code that im trying to make and im not sure of the things that i did but the output is correct. im just confused about the last part of the program where the name and score is being printed.
for (i=0; i<x; i++)
{
if(scores[i] == largesc)
cout<<endl<<"highest score is "<<name[i]<<" with "<<largesc<<" score."<<endl;
}
for (i=0; i<x; i++)
{
if(scores[i] == smallsc)
cout<<"lowest score is "<<name[i]<<" with "<<smallsc<<" score."<<endl;
}
My question is .. how come this loop and if statement helps the program to output the correct name?
for (i=0; i<x; i++)
{
if(scores[i] == smallsc)
cout<<"The lowest score is "<<name[i]<<" with "<<smallsc<<" score.";
if i don't put this ( the loop and if statement ) then the program will not output the correct name.. i just want to understand the codes... any help will be appreciated.
What? It shouldn't even compile: int scores[] = {}; is not valid C++. What compiler do you use?
And use code tags next time. It makes it easier to read.
To answer your question, it needs the for loop and if statement because you need to have i set to the correct value. What you need is to make "sentinel" variables that can be set to the value of your high and low spots in your array. (look for the variables hi and low in the example)
You might also want to work on indenting, it would have made it a bit easier to work with if this was a longer code.
int main()
{
int wait;
int scores[100];
string name[100];
int x, i;
cout << "How many students?: " ;
cin >> x ;
for(i=0; i<x; i++){
cout << "Enter Students " << i+1 << " name: " ;
cin >> name[i];
cout << "Enter Students " << i+1 << " score: " ;
cin >> scores[i];
}
int largesc = scores[0];
int smallsc = scores[0];
int hi = 0 , low = 0;
for(i=1; i<x; i++)
{
if(scores[i] > largesc)
{
largesc = scores[i];
hi = i;
}
elseif(scores[i] < smallsc)
{
smallsc = scores[i];
low = i;
}
}
cout<<endl<<"highest score is "<<name[hi]<<" with "<<largesc<<" score."<<endl;
cout<<"lowest score is "<<name[low]<<" with "<<smallsc<<" score."<<endl;
cin>>wait;
return 0;
}
I'm also curious what compiler you're using, it's pretty user-friendly if it would run after "int scores[] = {};" but it's also teaching you bad coding if it didn't throw an error for that.
line 6: intscores[] = {};
line 21: largesc = score[i];
It wont work.
After fixing errors it works fine.
As for your question:
in first part of the program you have saved high and low values but haven't saved their indexes. So you know that lowest score is, say, 40, but don't know, who has such score.
Part you have questions with iterates over array and output names of people, whose scores equals lowest score and their score (lowest). If there is one people with lowest score it will output him. If there is two, it will outpur both and so on.