简体   繁体   中英

Using arrays with for-loops

Questions:

  1. why is the first "cin >>" having "score[0]" saved to it? Since the program is asking for 5 numbers, wouldn't it make sense to save the entered numbers into an array of 5 ("score[4]")?

  2. I also don't understand the syntax of the second "cin >> score[i]." I thought "cin>>" was coupled with "cout<<" when there was data input.

//Enter five scores. Show how much each differs from the highest score.
#include <iostream>
using namespace std;
    
int main()
{
    int i, score[5], max;
        
    cout<<"Enter 5 scores:\n";
    cin >> score[0];
    max = score[0];
        
    for (i = 1; i < 5; i++)
    {
        cin >> score[i];
        if (score[i] > max)
            max = score[i];
    }
        
    cout <<"Highest score: " <<max<<endl
         <<"The scores and their\n"
         <<"diff. from highest are:\n";
        
    for (i = 0; i < 5; i++)
        cout << score[i] << " off by "
             << (max - score[i]) << endl;
    
    return 0;        
}

cin is stdin . This is a UNIX thing. Basically it's the input to your program. If you don't do anything else, it's your console or terminal session.

cout is stdout , another UNIX thing. It's output. Again, your console or terminal session if you don't do anything else with it. They aren't really coupled. It's two separate things, one for input only, one for output only.

Now, let's look at your code:

cin >> score[0];
max = score[0];
    
for (i = 1; i < 5; i++)
{
    cin >> score[i];
    if (score[i] > max)
        max = score[i];
}

This could be simplified. You could get rid of the first two lines and change it to just this:

for (i = 0; i < 5; i++)
{
    cin >> score[i];
    if (score[i] > max)
        max = score[i];
}

You'll just have to initialize max to a really negative value.

What cin >> does here is read a SINGLE value -- one score -- and then you stuff it into a single member of score . So you can NOT do something like this:

cin >> score;

That just won't work. Well, you might be able to make it work with operator overloading, but that's an advanced topic, and I've never tried. (I frankly never use the >> operator but find other ways to get input.)

Another thing: score[4] refers not to an array of size 5, but to the 5th item in the array, just like score[0] refers to the first item. It only refers to the size in the initial definition:

int score[5];

That's the only time the [5] is about the size. Otherwise it's an index into the array, starting at 0. So you have score[0] ... score[4] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM