Programming chapter 4
Programming chapter 4
January, 2013
Array Definition
Like other normal variables, the array variable must be defined before its use. The syntax for
defining an array is:
Data type ArrayName[array size];
In the definition, the array name must be a valid C++ variable name, followed by an integer
value enclosed in square braces. The integer value indicates the maximum number of elements
the array can hold. The following are some valid array definition statements:
int marks[100]; //integer array of size 100
float salary[25]; //floating-point array of size 25
char name[50]; //character array of size
double[10]; // double array of size 10
N.B. Arrays of any data type can be defined.
Here is a definition of an array of integers: int hours[6]; The name of this array is hours. The
number inside the brackets is the array’s size declarator. It indicates the number of elements, or
values, the array can hold. The hours array can store six elements, each one an integer. This is
depicted in Figure below.
hours array: Enough memory to hold six int values
Page | 1
Fundamentals of Programming
January, 2013
An array’s size declarator must be a constant integer expression with a value greater than zero. It
can be either a literal, as in the previous example, or a named constant, as shown here:
int hours[SIZE];
Page | 2
Fundamentals of Programming
January, 2013
Note:
Subscript numbering in C++ always starts at zero. The subscript of the last element in an array is
one less than the total number of elements in the array. This means that in the array shown
above, the element hours[6] does not exist. The last element in the array is hours[5] .
Array initialization
Arrays may be initialized when they are defined as follows:
DataType array-name[size]={list of values separated by comma};
For instance the statement: int age[5]={19,21,16,1,50}; defines an array of integers of size 5. In
this case, the first element of the array age is initialized with19, second with 21 and so on. A
semicolon always follows the closing brace. The array size may be omitted when the array is
initialized during array definition as follows:
int age[]={19,21,16,1,50};
in such case the compiler assumes the array size to be equal to the number of elements enclosed
within the curly braces.
Page | 4
Fundamentals of Programming
January, 2013
Page | 7
Fundamentals of Programming
January, 2013
Page | 8