An array is a variable that can store multiple values. An array is defined as the collection of similar types of data items stored at contiguous memory locations. which can store the primitive type of data such as int, char, double, float, etc.
Syntax:
data_type array_name[array_size];
Example:
#include<stdio.h>
#include<conio.h>
Void main()
{
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}
getch();
}
Types of Arrays in C
1. Single Dimensional Array / One Dimensional Array
2. Multi-Dimensional Array
One Dimensional Array
Example:
#include<stdio.h>
#include<conio.h>
Void main()
{
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}
getch();
}
Multi-Dimensional Array
we can define multidimensional arrays in simple words as an array of arrays. Data in multidimensional arrays are stored in tabular form (in row-major And column order).
Syntax:
data_type array_name[size1][size2][size3]..[sizeN];
Examples:
Two-Dimensional Array
int two_D[2][3];
Three-Dimensional Array
int three-D[2][3][3];
Two Dimensional Array
Int arr[3][3];
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
// an array with 3 rows and 2 columns.
int x[3][2] = {{0,1}, {2,3}, {4,5}};
int I,j;
// output each array element's value
for ( i = 0; i < 3; i++)
{
for (j = 0; j < 2; j++)
{
printf(“%d”,x[i][j]);
}
}
return 0;
}
Three Dimensional Array
Int arr[3][3][3];
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
// initializing the 3-dimensional array
int I,j,k;
int x[2][3][2] =
{
{ {0,1}, {2,3}, {4,5} },
{ {6,7}, {8,9}, {10,11} }
};
// output each element's value
for ( i = 0; i < 2; ++i)
{
for (j = 0; j < 3; ++j)
{
for ( k = 0; k < 2; ++k)
{
printf(“%d”,x[i][j][k]);
}
}
}
return 0;
}
0 Comments