Arrays

In this tutorial, we are going to talk about arrays. C programming language provides a special data structure called the array. An array lets you declare and work with a collection of values of the same data type.
Let’s say you want to declare 5 integers and assume that we don’t have array concepts. We will write like below.

int a,b,c,d,e;

now you want to declare 1000 variables of same data type.Are you ready to type a thousand variables like above?  With the help of array, we can easily declare our 5 variable like this.

int a[5];

Array classified into two categories.

  1. Single Dimensional Array
  2. Multi-Dimensional Array.

Declaration:

syntax:

data_type variable_name[array_size];

This type of array is called as single dimensional array.

Array size should be an integer and greater than zero.

Initializing Arrays:

You can declare an array one by one or in a statement.

int age[3];

age[0] = 10;

age[1] = 20;

age[2] = 30;

(OR)

int age[3] = {10,20,30};  // the number of values inside the {,} can not be greater than array size declared with in [].

(OR)

int age[] = {10,20,30};

program:

#include
int main ()
{
int age[ 5 ]; /* age is an array of 5 integers */
int i,j;
/* initialize age */
for ( i = 0; i < 5; i++ )
{
age[ i ] = i + 10;

}
/* output each array element's value */
for (j = 0; j < 5; j++ )
{
printf("age[%d] = %d\n", j, age[j] );
}
return 0;
}

output:

age[0] = 10
age[1] = 11
age[2] = 12
age[3] = 13
age[4] = 14

Multi-Dimensional Array:

C programming allows multi-Dimensional array,

syntax:

data_type variable_name[size1][size2]……[size_n];

To understand easily lets take Two Dimensional array. It can be illustrated in matrix like this image

7d7d2 two array bmp 300x150

Declaration:

int a[2][3];  // 2 rows 3 columns

Initialization:

int a[2][3] = { 0,1,2  /* row 1*/

3,4,5} /* row 2*/

program:

#include
int main()
{
int a[2][2], i , j;
for (i = 0; i < 2; i++)
{
for ( j = 0; j < 2; j++)
{
a[i][j] = i+j;
printf("a[%d][%d] = %d \n", i, j, a[i][j]);
}
}
return 0;
}

output:

a[0][0] = 0;

a[0][1] = 1;

a[1][0] = 1;

a[1][1] = 2;

Passing Arrays as Function Arguments:

We can pass arrays as arguments to a function as follows.

void myFunction(int param[])
{
.
.
}

program:

#include

/* function declaration */
int getTotal(int arr[], int size);

int main ()
{
/* an int array with 5 elements */
int values[5] = {10, 2, 3, 5, 50};
int  sum;

/* pass pointer to the array as an argument */
sum = getTotal(values,5 ) ;

/* output the returned value */
printf( "Total value is: %f ", sum );

return 0;
}

int  getTotal(int arr[], int size)
{
int    i;
int  sum;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
return sum;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *