Professional Documents
Culture Documents
Arrays CPP
Arrays CPP
ARRAYS:
-An array is defined as the collection of similar type of data items stored at
contiguous memory locations.
- Arrays are the derived data type in C++ programming language which can
store the primitive type of data such as int, char, double, float, etc.
-It also has the capability to store the collection of derived data types, such
as pointers, structure, etc.
-The array is the simplest data structure where each data element can be
randomly accessed by using its index number.
ONE DIMENSIONAL ARRAY:
SYNTAX:
Data_Type array_name[array_size];
EXAMPLE
int marks[9]={40,55,63,17,22,68,89,97,89};
MEMORY SIZE OF ARRAY=TOTAL NO
OF ELEMENTS IN ARRAY*DATATYPE
SIZE
// Array declaration by specifying size
int arr1[10];
INITIALIZATION OF ARRAY
FIRST METHOD:
marks[0]=80;
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
SECOND METHOD:
for(i=0;i<5;i++)
{
cin>>marks[i];
}
EXAMPLE OF 1 D ARRAY
int main()
{
int values[5];
printf("Enter 5 integers: ");
// taking input and storing it in an array
for(int i = 0; i < 5; ++i)
{
cin>>values[i];
}
// printing elements of an array
for(int i = 0; i < 5; ++i)
{
cout<<values[i];
}
}
MULTI DIMENSIONAL ARRAYS
• Arrays of arrays.(ie) an array containing one or more arrays.
SYNTAX:
Data_Type array_name[1st dimension][2nd dimension][]..[Nth
dimension] ;
TWO DIMENSIONAL ARRAYS:
First Method:
Second Method:
Third Method:
int x[3][4];
for(int i = 0; i < 3; i++){
for(int j = 0; j < 4; j++){
cin>>x[i][j];
}
}
EXAMPLE OF 2D ARRAY
int main()
{
int disp[2][3];
int i, j;
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
cout<<"Enter values for array”;
cin>>disp[i][j];
}}
cout<<"Two Dimensional array elements:\n";
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
cout<< disp[i][j];
}
}
}
3D Arrays
Example:
int arr[3][3][3];