Filling an Array
 | |  | | |
#include <iostream.h>
int main()
{
int anArray[5];
int i;
cout <<"Enter 5 numbers to fill the array.";
for(i = 0; i < 5; i++)
{
cout << “anArray[“ << i << “]” << “n”;
cin >> anArray[i];
}
for(i = 0; i < 5; i++)
{
cout <<"Here are the numbers in the array.
cout <<"anArray[" << i << "]" << anArray[i] << "n";
}
return 0;
} |
|  |
|
In this example, I created an array that stored 5 integer elements. I created a for loop to allow the user to enter 5 numbers into the array. The second for loop I created was to display the contents of the array. The cin >> anArray[i]; is where the array got filled each time the for statement loops.
(The array looks like this if you entered these 5 numbers: 4, 5, 7, 30, and 40. )
| anArray |
Numbers You Entered: |
| 4 |
5 |
7 |
30 |
40 |
| 0 |
1 |
2 |
3 |
4 |
(This shows the values you entered on top, and the index values on the bottom of the table.) Please Rate this Code: