Chapter 6 - Arrays
Chapter 6 - Arrays
Chapter 6 – Arrays
Arrays are used to store a collection of variables all of the same type. For instance you
can have arrays that store numbers, words etc.
int number[12] //This array is called numbers and will store 12 integers
char name[10] //This array is called names and will store 9 characters plus \0
Each member in the array has an index number. This index number is used to access
the value of that member.
In general if an array has N members then the first member has index 0 and the last
has index N-1.
You can assign values to each member just as with other variables
arr[0] = 10;
arr[3] = 3;
These two lines will set the first member of arr equal to 10 and the fourth equal to 3.
You can initialise an array at the same time as you are defining it as follows:
arr[0] = 11;
arr[1] = 2;
arr[2] = 6;
arr[3] = 7;
arr[4] = 3;
1 #include<iostream.h>
2 int main()
3 {
4 const int SIZE=5;
5 int arr[SIZE];
6 int i;
7 int sum
8 sum=0; //We must initialise sum to zero
9
10 for(i=0; i<SIZE; i++)
11 {
12 cout<< "Enter a number" <<endl;
13 cin>>arr[i];
14 }
15
16 for(i=0; i<SIZE; i++)
17 {
18 sum=sum+arr[i];
19 }
20
21 cout<< "The sum of the five numbers is " << sum <<endl;
22
23 return 0;
24 }
Example 6a
When you enter in 5 numbers the program will print out the sum of those 5 numbers.
The line "const int SIZE=5;" is used in case the size of the array needs to be changed -
then only one value will need to be changed. The const keyword means that SIZE is a
Beginners Guide to C++ - Chapter 6
constant and not a variable. Constants are usually written in CAPITAL letters and
here I have also coloured the constant orange for clarity.