Arrays in C

Arrays in C

If we need to declare many variables of same data type then we use arrays.
Suppose, we want to store marks of 100 students then it is not good way to declare 100 variables and store values in them.
So, here array comes into picture.

Array is collection of variables of same data type.

Following are important things to know about array:

  • They have same data type.
  • They have continuous memory allocation.
  •  All variables have same name and are distinguished by subscripts
  • It always starts with 0 and ends with (n-1)th element.


Syntax:

data_type variable [size];


e.g:

int arr[50];
float a[100];

How to calculate array size?

To calculate array size we need to multiply size of array with datatype size.
In above case,

float a[100];

So, here if we want to calculate how much space is required we know:
size of array a is 100.
size of float is 4 bytes.

Thus, total size required to store this array is: size of array * size of float
i.e. 100*4 =400 bytes.


Types of arrays:

Their are 3 types of arrays:

  • 1 D arrays
  • 2 D arrays
  • Multidimensional arrays
Declaration of 2 D arrays is same as syntax shown above just change is we have to create one more size parameter.
e.g:
int ar[5][9];
It creates an array of 5 rows and 9 column.

Similarly, we can create array of any dimensions using as much size parameters i.e. [] we want.
This forms multidimensional array.

e.g:
int arr[2][24][18][3][7];
This is multidimensional array.

Recommended try programs below (click on programs for solutions):

1 D arrays:


2 D arrays:




No comments:

Post a Comment