Arrays

Blog Contents

Arrays

An array is a collection of similar data which is stored in sequential order in the memory. For example, if we save one integer variable into memory it will occupy 4 bytes. If we make another variable then it also occupies 4 bytes, but this memory of two variable may be consecutive or maybe not. This type of variable declaration method is alright until we are having less number of variables.
Once we have to handle the number of variables, it’s maybe 50, 100 then making 50 variable is very difficult.
                int a,b;
We have a solution, we can make an array of N number of the element. In the array, all variable will be saved into consecutive memory locations.

Declaration of array

datatype arrayname[sizeofarray];
Ex:int array[50];
array stored in memory.
array program example
This will reserve 50th places each of size 4 bytes int memory and the good part is all are consecutive in memory locations.
You can initialize an array in C either one by one or using a single statement as follows
marks[5]={47,48,45,44,49};
Or marks[5];
marks[0]=47;, marks[1]=48; marks[2]=45;, marks[3]=44;,marks[4]=49.
How to access this element? This is very simple,
We can access each element individually by showing their place value.
E.g. array[1], array[0], array[24] etc.
Keep remember array always starts from 0, means the first element is always array[0] and last-element is one less than the maximum number element, in our case array[49].

Let’s see the program using the array which explains the declaration, assignment and accessing the array;

#include<stdio.h>
Int main(void)
{
Int a [12]; /* a is array of 12 integers*/
Int I,j; /* I and j are integers*/
/*initializing the values to array elements a */.
for(i=0;i<12;i++)
{
a[i]=i+10; /* assigning value i+10 to ith element*/
}
/* printing the values of elements of array a*/
For(j=0;j<12;j++)
{
Printf(“a[%d]=%d”,j,a[j]);
}
Return 0;
}

Output:

a[0]=10;
a[1]=11;
a[2]=12;
a[3]=13;
a[4]=14;
a[5]=15;
a[6]=16;
a[7]=17;
a[8]=18;
a[9]=19;
a[10]=20;
a[11]=21;

Passing array to function

We can pass array elements to function in two ways. One is bypassing a single value or by passing the full array.
Passing single value to array
#include<stdio.h>
Void foo(int a)
{
printf(“a=%d”,a)
}
Int main (void)
{
Int array[]={1,2,3};
foo(array[1]); // array[1] is passed to the called function foo
Return 0;
}

Output:

a=2;

Passing Entire Array to Function

#include<stdio.h>
Int main(void)
{
Int a[5]={1,2,3,4,5};
Sum=add(a); // passing full array to called function
Printf(“sum=%d”,sum);
return 0;
}
Int add(int a[])
{
Int sum=0, i;
for(i=0;i<5;i++)
{
Sum=sum+a[i];
}
return sum;// return sum to main function.
}

Output

Sum=15;