Tuesday, 23 January 2018

Type of Arrays in C language

Welcome back! In my last post i tell you about C Array after that i want to explain you the types of C Arrays. So let's start....

There are three types of Array,
1) One-dimensional Array
2) Two-dimensional Array

One-dimentional(1D) Array:

A  list of items can be given a common name and the individual items can be referenced using only one subscript. Such variable are referred to a single subscript varriable or a One dimensional array.
The liner arrays are also called one dimensional arrays, since each element in the array is referenced by a single subscript. The one dimensional array is the array in which the elements are represented in single row.

1) Declaration of C Array: 
We can declare an array in c language in the following way:

data_type array_name[array_size];
Now, Let's see the example to declare an array.
int mark[5];
Here, int is the data_type, mark is array_name and 5 is array_size

2) Initialization of C Array:
A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

mark[0]=80;//Initialization of array
mark[1]=75
mark[2]=85
mark[3]=65
mark[4]=90

Example of 1D Array:


#include<stdio.h>

int 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]);
}
//end of for loop
return 0;
}

Two-dimensional(2D) Array:


Array are used to store the data item in the form of a list by using the one-dimentional array, but some time we have to store the data in the tabular form, then for storing data in the tabular form C provides the concept of two-dimensional array. The two-dimensional array is also known as a matrix.
A 2D array is a grid having rows and columns in which each element is specified by two subscripts. It is the simplest of multi-dimensional arrays.

1) Declaration of 2D Array in C:
We can declare an array in the c language in the following way:

data_type array_name[size1][size2];

A simple example to declare two dimensional array is given below:
int twodimen[4][3];
Here, 4 is the row number and 3 is the column number.

2) Initialization of 2D Array:
A way to initialize the two dimensional array at the time of declaration is given below:
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Example of 2D Array:

#include<stdio.h>
int main()
{
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++)
{
 for(j=0;j<3;j++)
{
   printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
 }
//end of j
}
//end of i
return 0;
}

0 comments:

Post a Comment