LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   C++ Six Element Array (http://www.linuxquestions.org/questions/programming-9/c-six-element-array-83799/)

petercool 08-20-2003 09:10 AM

C++ Six Element Array
 
In the following code I don't understand why the variable index is needed. Also in the 'for loop' when the array is ouputed to the vdu via cout, why does it need to be 'number[index].'

#include <iostream.h>

main()
{
int number[6]; // an array of integers
int index;

number[5] = 42; //initialize the arrray
number[4] = 2001;
number[3] = 7;
number[2] = 180;l
number[1] = 99;
number[0] = 1993;

for (index = 0; index <= 5; index++)
{
cout << number[index] << endl;
}
return(0);
}

Thanks in advance my book didn't explain this section of code.

nephilim 08-20-2003 09:31 AM

I'll try to explain it step by step:

index = 0: sets the index variable to 0 (duh)
index <= 5: as long as this condition is met, the for loop will be executed
index ++: after each loop, the index variable is increased by 1

number[index] is the location location in the number array, so when index = 0, number[index] = 1993, when index = 1, number[index] = 99 and so on.

cout << number[index] << endl

will print the content of the array at the location of index to the screen and it will do this as long as index <= 5.
The endl is a newline so that the next element will be printed on a new line.

I hope this explains things to you...

petercool 08-20-2003 12:08 PM

Ty!
 
Thanks I understand now! :)


All times are GMT -5. The time now is 12:35 PM.