Arrays

When variables have the same function in a program, it is often more efficient to use an array.

The program below reads in three numbers, and then prints them.

The statement double num[3]; allocates space in memory for three decimal numbers. The three numbers are referred to as num[0], num[1], and num[2].

array

The number inside brackets is the subscript or index. The subscripts always start with 0.

Once a variable is declared as an array, the subscript must be included to refer to the elements.

One of the advantages of an array is that the subscript can be a variable. A for loop can be used to read in an array of numbers or print them out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//Arrays: Read 3 numbers
#include<iostream>
using namespace std;
int main() {
   double num[3];
   for(int i=0;i<3;i++) {
     cout<<"Enter a number: ";
     cin>>num[i];
   }
   for(int i=0;i<3;i++) {
     cout<<num[i]<<endl;
   }
   system("pause");
   return 0;
} //main
CODE

NEXT: Input and Arrange