+ 1
C++ Arrays and cin
Why is it possible to enter numbers inside a single index of an array like this ? Please clarify what is going on here and how is this possible? int score[5]; cout << "Enter 5 scores: " << " "; cin >> score[0]; // Why score[0] holds so many elements at one index only ? max = score[0]; To me, I always thought that I can only enter one element per index of an array.
5 Réponses
+ 12
That example is flawed. You are correct, an index will only hold one element.
score[0] will only hold one value. In order to do what he/she wants to do, you'll need to utilise a loop.
cout << "Please input 5 scores" << endl;
for (int i = 0; i < 5; i++)
{
cin >> score[i];
}
cout << endl;
+ 8
I see. That sure is the weird way of doing it. What the book did was to assign the first input value to both score[0] and max, and the rest of the 4 values to the remaining arrays. While it works, I see better ways to solve the problem.
+ 2
Yes, I completely agree with you. But in an example in my book, the c++ code is trying to give score[0] some values using cin. Then setting max = score[0] and then using a for loop and if statement inside, it tries to find out what is the highest value of the numbers that were entered before.
This is the code;
int score[5];
cout << "Enter 5 scores: " << " ";
cin >> score[0];
max = score[0];
for (int i = 1; i < 5; i ++){
cin >> score[i];
if (score[i] > max){
max = score[i];
}
cout << "The highest score is: " << max;
link code;
cpp.sh/37egn
I think, i would have been more comfortable writing it in another format, I am never used to this way of syntax. Do you know a better way?
+ 2
Yeah, there is so much variety in codes for the same output, I guess the more you know, the better you get.
+ 1
@Kenyatta, man I have hard time understanding the cin approach too, but it works.
You know you are a programmer when your code works, but you have no idea how.