Sams Teach Yourself C++ in 21 Days

(singke) #1
Managing Arrays and Strings 409

13


LISTING13.1 Using an Integer Array


0: //Listing 13.1 - Arrays
1: #include <iostream>
2:
3: int main()
4: {
5: int myArray[5]; // Array of 5 integers
6: int i;
7: for ( i=0; i<5; i++) // 0-4
8: {
9: std::cout << “Value for myArray[“ << i << “]: “;
10: std::cin >> myArray[i];
11: }
12: for (i = 0; i<5; i++)
13: std::cout << i << “: “ << myArray[i] << std::endl;
14: return 0;
15: }

Value for myArray[0]: 3
Value for myArray[1]: 6
Value for myArray[2]: 9
Value for myArray[3]: 12
Value for myArray[4]: 15
0: 3
1: 6
2: 9
3: 12
4: 15
Listing 13.1 creates an array, has you enter values for each element, and then
prints the values to the console. In line 5, the array, called myArray, is declared
and is of type integer. You can see that it is declared with five in the square brackets. This
means that myArraycan hold five integers. Each of these elements can be treated like an
integer variable.
In line 7, a forloop is started that counts from zero through four. This is the proper set
of offsets for a five-element array. The user is prompted for a value on line 9, and on line
10 the value is saved at the correct offset into the array.
Looking closer at line 10, you see that each element is accessed using the name of the
array followed by square brackets with the offset in between. Each of these elements can
then be treated like a variable of the array’s type.
The first value is saved at myArray[0], the second at myArray[1], and so forth. On lines
12 and 13, a second forloop prints each value to the console.

OUTPUT


ANALYSIS
Free download pdf