Arrays in C

In this section of the tutorial, we will discuss a very important derived data type called Arrays used in C programming language to perform operations that includes handling a large number of data values.

We will understand the concept of Arrays, how we can declare it, initialize it, and access it in a program with the help of examples for better understanding.

Now, let’s move on further to discuss the concept of Arrays in C programming language.

What are Arrays?

An array is a fixed-sized, structured, and sequential collection of elements of the same kind of data type that share a common name. Since it has a structured form, it can be used in representing values that have a structure of some sort.

  • Arrays are one of many derived data types called data structures including others like stacks, queues, linked lists, trees, etc.
  • Some times we write a program where we need to handle large volumes of data in terms of reading, processing, and printing.
  • So to process such a large amount of data, we need a powerful derived data type that would facilitate efficient storing, accessing, and manipulation of data items. Hence, we use Arrays to carry out such big tasks.

How do we declare Arrays?

Now, we have to declare an array first before we use it in a program. Declaring an array allocates the memory required by the user to store data in the program.

The general form of array declaration: data type variable-name[size];

  • Here, data type indicates the type of data we want to store such as int, float, or char.
  • variable-name indicates the name of the array.
  • size indicates the maximum required size of the array we want to store data in.
  • Lastly, we must use a semicolon ‘;’ at the end to declare an array without any syntax error.

Example:

int Marks[5]

float height[20]

char name[15]

We will understand how we can declare arrays with the help of an example given below.

Index values of Array elements

  • Index values numbers used to represent a list of items in an array sharing a common name.
  • Any array always begins with index value 0.
  • Index values of an array could be an integer constant, integer variables like i,j, or any expression that yields integer value starting from 0.

We will understand how we can access array elements using the index values with the help of an example given below.

If we declare an array like int Marks[5];
It means the following distribution has occurred in the memory of the computer:

Marks[0]
Marks[1]
Marks[2]
Marks[3]
Marks[4]

So, the array will store data values in the same manner as the array index value distribution given above.

How can we initialize Arrays?

Now, we must initialize an array to avoid garbage value storage and further discrepancy in the evaluation of data in the program.
An array can be initialized in either of two ways in a program:

  • Compile Time Initialization
  • Run Time Initialization

Now, we will discuss each way to initialize an array in detail.

Compile Time Initialization

Arrays can be initialized in the same way that any other variables are initialized at the beginning of a program.

General form of array initialization can be: datatype array-name[size]={list of values};

  • Here, datatype indicates the type of data values that are to be stored in the array.
  • array-name indicates the name of the array.
  • size indicates the size of the array.
  • list of values indicates the values taken as input that are to be stored in the array.
  • The initialization must end with a semicolon ‘;’.
  • Each value in the list of values must be separated with a comma ‘,’.
  • If the number of values inputted are less than the size of the array, then the remaining space of elements are set to zero by default.
  • It is not allowed to input more values in an array than the declared array size, in such a case, it will produce errors in the program and it will lead to the condition of buffer overflow.

We will understand how we can initialize an array in compile time with the help of an example given below.

Example: int Marks[5] = {10,20,30,40,50};

Then following distribution can be assumed for a better understanding of memory allocation:

Marks[0]=10;
Marks[1]=20;
Marks[2]=30;
Marks[3]=40;
Marks[4]=50;

  • In the above distribution, each element of the index value starting from 0 stores a data of type int.
  • If we remove the value 40 from Marks[4], then Marks[4] will be assigned 0 automatically.
  • If we store an extra value such as 60 at initializing the array exceeding the array size, it will produce an error in the program.

Run Time Initialization

Arrays can also be initialized at run time of the program, this method is more preferable to use when storing a large number of data values.

We will understand how we can initialize an array in run time with the help of an example given below.

Generally, we use loop statements or function scanf() or a combination of them to assign values in an array.

Few examples is given below:

Using loop statements:

for(i = 0; i < 50; i++)

{

   if(i < 25)

      Marks[i] = 0;

   else

      Marks[i] = 1;

}

Using function scanf():

scanf(“%d%d%d…”,&Marks[0],&Marks[1],&Marks[2],…);

How can we access Array elements?

The data stored inside the elements of an array can be accessed using the index values assigned to each element.

For example, if we declared an array such as, int Marks[5] = {70,75,80,90,95};
Then we can access any particular element using its index number. Like if we want to access the 3rd element of the given array,
we can use Marks[2].

In general, for accessing an nth element we can use array_name(n-1)th index number.

We will understand how we can access array elements with the help of an example given below.

How can we use Arrays in a program?

Arrays can be used in several operations where a large amount of data are to be handled in a program.

Arrays are used frequently in searching and sorting operation where a large pool of data values are taken by the program to sort these data values in a particular order or find a particular value among many data values.

Few basic sorting techniques used are:

  • Bubble sort
  • Selection sort
  • Insertion sort

Two most commonly used searching techniques are:

  • Sequential search
  • Binary search

What are multi-dimensional Arrays?

Arrays can be created of more than one dimension for storing a list of values in a tabular form in terms of rows and columns. The exact limit of the number of dimensions is determined by the compiler.

The general form of a multi-dimensional array: datatype array_name[s1][s2][s3]…[sn];

  • Here, datatype indicates the type of data that is to be stored in the multi-dimensional array.
  • array_name indicates the name of the array.
  • s1,s2,s3,..,sn indicates the respective sizes of each dimension in the array
  • n indicates the total number of dimensions in the array.

Example:

int Table[3][4][5][6];

We will understand how we can use a multi-dimensional array with the help of an example given below.

Few examples on Arrays

Example: Program to store the count of students in different sections of a class using Arrays.
Sample code:
#include<stdio.h>
int main()
{
    int Class[4]={45,50,60,70};
    int i;
    for (i = 0; i < 4; i++)
    {
        printf("Class %d = %d\n",i+1,Class[i]);      
    }
    return 0;
}
Output:
Class 1 = 45
Class 2 = 50
Class 3 = 60
Class 4 = 70
Example: Program to add two matrices and print their sum in the third matrix using Arrays.
Sample code:
#include<stdio.h>
int main()
{
    int i, j,r=2,c=2,A[r][c],B[r][c],C[r][c];
    printf("Enter elements of first Matrix A: \n");
    for(i = 0; i < r; i++)
    {
        for(j = 0; j < c; j++)
        {
            scanf("%d", &A[i][j]);
        }        
    }
    printf("\nEnter elements of Matrix B: \n");
    for(i = 0; i < r; i++)
    {
        for(j = 0; j < c; j++)
        {         
            scanf("%d", &B[i][j]);
        }                
    }
    printf("\nMatrix C:\n");
    for(i = 0; i < r; i++)
    {
        for(j = 0; j < c; j++)
        {
            C[i][j]=A[i][j]+B[i][j];
            printf("%5d ",C[i][j]);            
        }        
        printf("\n");
    }       
    return 0;
}
Output:
Enter elements of first Matrix A: 
1
2
3
4

Enter elements of Matrix B: 
1
2
3
4

Matrix C:
    2     4 
    6     8
Example: Program to read a matrix and print its transpose using Arrays.
Sample code:
#include<stdio.h>
int main()
{
  int i,j,a[3][3],b[3][3];
  printf("Enter the values below: \n");
    for ( i = 0; i < 3; i++)
    {
      for ( j = 0; j < 3; j++)
      {
        printf("a[%d][%d]: ",i,j);
        scanf("%d",&a[i][j]);
      }
    }
    printf("\nEntered matrix is: \n");
    for ( i = 0; i < 3; i++)
    {
      printf("\n");
      for ( j = 0; j < 3; j++)
      {
        printf("%d\t",a[i][j]);
      }
    }
    for ( i = 0; i < 3; i++)
    {
      for ( j = 0; j < 3; j++)
      {
        b[i][j]=a[j][i];
      } 
    }
    printf("\nTranspose of the matrix is: \n");
    for ( i = 0; i < 3; i++)
    {
      printf("\n");
      for ( j = 0; j < 3; j++)
      {
        printf("%d\t",b[i][j]);
      }
    }
    return 0;      
}
Output:
Entered matrix is: 

1       2       3
4       5       6
7       8       9
Transpose of the matrix is: 

1       4       7
2       5       8
3       6       9

Passing Arrays to Functions

Arrays can be passed to Functions in the same way as we pass normal variables to a function.

To pass an Array to a called Function, we just have to follow the process given below:

  • Listing the name of the Array without its index values.
  • Specifying the size of the arrays as Function arguments, but not necessary.

The general form for passing Array to Function could be:

datatype function-name(datatype array-name[])

Below is an example for us to understand how we can pass an Array to a Function.

Example: Passing a single element of an Array to called Function.

Sample Code:

#include<stdio.h>

void Array1(int a);

int main()
{
    int a[] = {10,20,30};
    Array1(a[1]);
    return 0;
}

void Array1(int n)
{
    printf("%d\n",n);
}

Output:

20

Example: Passing a complete Array to called Function.

Sample Code:

#include<stdio.h>
int FindVal(int a[], int n);

int main()
{
    int FindVal(int a[], int n);

    int a[4] = {10,20,30,40};

    printf("%d\n",FindVal(a,4));
}

int FindVal(int a[], int n)
{
    int i;
    int max;
    max = a[0];
    for ( i = 1; i < n; i++)
    {
        if(max < a[i])
        max = a[i];
    }
    return(max);
}

Output:

40

Important points to note:

  • If a called Function changes the values of the elements of an Array, then these changes will modify the values present in the Original Array too.
  • This happens because when an entire Array is passed as an argument to the called Functions, the values are not copied, instead, the address of the Array elements is passed into the formal parameter.
  • So any changes made in the Arrays will modify the values of the Original Array present in the calling Function too.
  • However, this case is not applied if an individual element is passed on as an argument to the called Function.
  • Also, we cannot pass the whole Array by value to the called Function.

Passing addresses to the function is referred to as pass by address or pass by pointers, which we will learn in detail in the Pointer in C tutorial section.

Rules to pass an array to functions

However, there is a set of rules that must be kept in mind before we pass an Array as arguments to the called Function.

  • Only the name of the Array must be passed to the called Functions.
  • In the Function definition, the formal parameter must be an Array type, where specifying the size of the Array is not necessary.
  • The Function prototype must show the Array as an argument.

Passing Multi-dimensional Arrays to Functions

Below is an example for us to understand how we can pass a multi-dimensional Array to a Function.

Example: Passing a multi-dimensional Array to called Function.

Sample Code:

#include<stdio.h>

void Disp(int arr[4][4]);

int main()
{
    int a[4][4], i, j;
    printf("Enter 16 array elements: \n");
    for (i = 0; i < 4; ++i)
    {
        for (j = 0; j < 4; ++j)
        {    
            scanf("%d", &a[i][j]);
        }
    }
    Disp(a);
    return 0;
}

void Disp(int a[4][4])
{
    int i, j;
    printf("Array entered is: \n");
    for (i = 0; i < 4; ++i)
    {
        printf("\n");
        for (j = 0; j < 4; ++j)
        {       
            printf("%d\t", a[i][j]);
        }
    }
}

Output:

Enter 16 array elements: 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Array entered is: 

1       2       3       4
5       6       7       8
9       10      11      12
13      14      15     16

Rules to pass a multi-dimensional Array to Functions

Similar to the rules of simple Arrays, a multi-dimensional Array must also follow the rules given below.

  • Only the name of the Array must be passed to the called Functions.
  • In the Function definition, the formal parameter must be a multi-dimensional Array with two sets of brackets.
  • The size of the second dimension of the Array must be specified in the formal parameter.
  • The Function prototype must show the multi-dimensional Array as an argument.

In the next section, we will discuss the concept of Pointers in C programming language.