Could someone please walk me through the following program. It's only 15 lines. My comments and questions are below dealing mostly with the array and "for" loops. Hopefully my questions make sense as I'm am so confused they may not be clear. I know the code works as I copied it straight from a book and ran it. I just can't follow what it's doing and I need to in order to do an assignment.
Here's my understanding;
Line 2, initializes an array called "item" with 5 components.
Lines 3,4 - initializes two variables
Here's where I'm really confused'
Line 8 - Initializes counter to zero, checks that counter is less than 5, if true then it advances the counter by one.
so in line 9 if you cin >> a number bigger than 5 why doesn't it prematurely end the "for" loop by make "counter" greater than 5?.
If counter is counting the components of the array, what variable is holding the user entered values.
Since sum = sum + item[counter]; is adding the user entered values it appears that counter is what is holding the user entered numbers. So then what is tracking the array components?
Lost in an array!
Code:
int main () { int item[5]; int counter; int sum; cout << " Enter 5 numbers: "; sum = 0; for (counter = 0; counter < 5; counter++) { cin >> item[counter]; sum = sum + item[counter]; } cout << endl; cout << " The sum of the numbers is : " << sum << endl; cout << " The numbers in reverse order are: "; for (counter = 4; counter >= 0; counter--) { cout << item [counter] << " "; cout << endl; return 0; }
Line 2, initializes an array called "item" with 5 components.
Lines 3,4 - initializes two variables
Here's where I'm really confused'
Line 8 - Initializes counter to zero, checks that counter is less than 5, if true then it advances the counter by one.
so in line 9 if you cin >> a number bigger than 5 why doesn't it prematurely end the "for" loop by make "counter" greater than 5?.
If counter is counting the components of the array, what variable is holding the user entered values.
Since sum = sum + item[counter]; is adding the user entered values it appears that counter is what is holding the user entered numbers. So then what is tracking the array components?
Lost in an array!
Comment