Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 18

ARRAYS IN C ++

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];

// declare an array of user specified size


int n = 10;
int arr2[n];

// Array declaration by initializing elements


int arr[] = { 10, 20, 30, 40};

// Array declaration by specifying size and initializing elements


int arr[6] = { 10, 20, 30, 40 };
int marks[5];//declaration of array 

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:

Data_Type  array_name [][]; 


int a[n][n];
TWO DIMENSIONAL ARRAY
int x[3][3];
Initializing Two – Dimensional Arrays:

First Method:

int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}

Second Method:

int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};

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];

3 tables each with 3 rows and 3 columns


JAGGED ARRAYS
- Ragged arrays
- Array of arrays such that member arrays can be of different sizes.
- 2-D arrays with variable number of columns in each row.
int s[4][];
s[0]={1};
s[1]={2,3};
s[2]={4,5,6};
s[3]={7,8,9,10};
arr[][] = { {0, 1, 2},
{6, 4},
{1, 7, 6, 8, 9},
{5} };

You might also like