ARRAY in C++: Kristina Jonas E. Mendoza
ARRAY in C++: Kristina Jonas E. Mendoza
int arrayname[5]
One-dimensional array
• A type of array in which all elements are arranged in the form of a list
is known as a 1-D array or single dimensional array or linear list.
• Declaring a single dimensional array:
data_type identifier[length];
• Example:
int samplearray[5];
Initializing a one-dimensional array
• The process of assigning values to array elements at the time of array
declaration is called array initialization.
• Syntax:
data_type identifier[length]={ list of values };
• Example:
int samplearray[5]={10,20,30,40,50};
0 1 2 3 4
int samplearray 10 20 30 40 50
Accessing elements of an array
• Individually
array_name[index];
• Example:
samplearray[2];
• Using loop
for (n=0; n<5; ++n) {
cout<<samplearray[n]<<endl;
}
Example programs
• Display individually
• Display using loop
• Compute the average of entered values
Two-dimensional array
• 2-D array can be considered as a table that consists of rows and
columns. Each element in 2-D array is referred with the help of two
indexes. One index indicates row and second indicates the column.
• Declaration:
data_type Identifier[row][column];
• Example:
int samplearray[3][4];
Syntax:
int samplearray[3][4]={ {12,5,22,30},{95,3,41,50},{77,6,53,45}};
0 1 2 3
0 12 5 22 30
1 95 3 41 50
2 77 6 53 45