Hello there, could some one explain the following array code, knowing i am new to the language.
mostly do not grasp code in line 15
15 for ( int i = 0; i < 10; ++i ), why he uses it, and is this effect final result j. plz explain.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
1 // Fig. 7.4: fig07_04.cpp
2 // Initializing an array in a declaration.
3 #include <iostream>
4 #include <iomanip>
5 usingnamespace std;
6
7 int main()
8 {
9 // use initializer list to initialize array n
10 int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
11
12 cout << "Element" << setw( 13 ) << "Value" << endl;
13
14 // output each array element's value
15 for ( int i = 0; i < 10; ++i )
16 cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl;
17 } // end main
The array n has 10 elements, so the valid index values for the array will run from 0 to 9 (total size minus 1). The for loop on line 15 prints out the current value of the index (variable i) and the value of the array at that index - it starts at 0 and runs up to 9.
wildblue has already provided a good answer, I am simply extending information: int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
is equivalent to:
1 2 3 4 5 6 7 8
int n[10];
n[0]=32;//1
n[1]=27;//2
n[2]=64'//3
//...
n[8]=60;//9
n[9]=37;//10
Arrays start count from 0, so an array of 10 would have indexes 0-9 (10 indexes).
Line 15, is a for_loop that has localized an integer variable of i=0, will repeat while i is less than 10, and will increment by 1 at the end of every cycle. The code it encapsulate would be a print out of i and the array value at index i.