A set of similar data types is called an array these data types can be of any initial type. The C language provides a capability that enables the user to design a set of similar data types, called array.There are 2 types of array
1.
One Dimensional array
It is a collection of data elements arranged in row is
called 1 D array.
2.
Two Dimensional array
It is a
collection of 1D array and arranged in row and column are 2d array.
1. One Dimensional array
Array Declaration
To begin
with, like other variables an array needs to be declared so that the compiler
will know what kind of an array and how large an array we want. In our program
we have done this with the statement:
int marks[5] ;
Accessing Elements of an Array
for ( i = 0 ; i <= 5 ; i++ ){
printf ( "\nEnter marks " )
;
scanf ( "%d", &marks[i]
) ;
}
Array Initialisation
So far we
have used arrays that did not have any values in them to begin with. We managed
to store values in them during program execution. Let us now see how to
initialize an array while declaring it. Following are a few examples that
demonstrate this.
int num[6] = { 2, 4, 12, 5, 45, 5 } ;
int n[ ] = { 2, 4, 12, 5, 45, 5 } ;
float press[ ] =
{ 12.3, 34.2 -23.4, -11.3 } ;
#include<stdio.h>
#include<conio.h>
void main(){
int i,v=0,a[5];
clrscr();
printf("Enter value of i=");
for(i=0;i<5;i++){
scanf("%d",&a[i]);
}
for(i=0;i<5;i++){
v=v+a[i];
}
printf("Sum is=%d",v);
getch();
}
Output
Enter value of i=6
10
4
20
8
Sum is=48
2. Two Dimensional array
The
simplest form of the multidimensional array is the two-dimensional array. A two-dimensional
array is, in essence, a list of one-dimensional arrays.
Array Declaration
How do we
initialize a two-dimensional array? As simple as this...
int arr[2][2]
Array Initialisation
Multidimensioned
arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row have 4 columns.
int arr[3][4] = {
{0, 1, 2, 3} ,
{4, 5, 6, 7} ,
{8, 9, 10, 11}
};
Accessing Elements of an Array
An element
in 2-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the array. For example:
for ( i = 0 ; i <= 5 ; i++ ){
for ( j = 0 ; j <= 5 ; j++ ){
scanf ( "%d", &arr[i][j]
) ;
printf ( "\nEnter marks " )
;
printf(“%d”,arr[i][j]);
}
}
Example of Two Dimensional array
#include<stdio.h>
#include<conio.h>
void main(){
int i,j,a[3][3];
clrscr();
printf("Enter elements in matrix=");
for(i=0;i<3;i++){
for(j=0;j<3;j++){
scanf("%d",&a[i][j]);
}
}
printf("\nElements in array=\n");
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("%d\t",a[i][j]);
}
printf("\n");
}
getch();
}
Output
Enter elements of matrix=9
8
7
6
5
4
3
2
1
Elements in array=
9 8 7
6 5 4
3 2 1
0 Comments