Array in C


August 23, 2021, Learn eTutorial
1439

In this tutorial you will learn everything about the data structure called an array. With the help of simple examples, you will understand how to declare, initialize and access variables from arrays.

What is an Array?

Array in C programming is a special kind of data structure that stores a finite set of elements of the same data type in sequential order.  More clearly we can define an array as a variable that stores multiple elements of the same datatype. 

Array

Arrays also referred to as structured data types come under the category of derived data types as it has the capacity to store both primitive data types such as int, char, float, double, etc and derived datatypes like pointers, struct, etc. The above image shows an array with 6 elements.

How to declare an array in C?

The general prototype of defining array is like--


data_type array_name[size of array in numbers];

See the below example :

int age[];
float sal[6];

Here the data type is int for the array age[] and the size of the array is not mentioned.

In the second case array, sal[6] creates six adjacent cells in memory which are sal[0], sal[1], sal[2], sal[3], sal[4], and sal[5] for storing the float type values.

The allocation of arrays starts with a 'null' and consequently the last variable of the series will be stored at a[size -1]. In our example, the first element of the array will be allocated at sal[0] and the last element will be allotted at sal[5].
 

Note: The size and type of array is perpetual once it is declared.

How to initialize an array in C

The next step after array declaration is the array initialization which can be done either at compile-time or at runtime. If an array is not initialized, it will contain any random values called garbage values in the memory.

Compile-time initialization of Array

The most convenient practice of initializing an array is defining the values of each element in the declaration statement itself. The array initialization syntax is
 


data_type array_name[size ] = {value_1st_element,value_2nd_element,3rd.....};
 

For instance ,


int age[] =  {25,27,29,30,35,37};   # integer array initialization
float sal[6] = {2500,2700,2900,3000,3500,3700}; #float array initialization
 

Run time initialization of Array

Run time initialization of arrays means users can input values during the execution of the program. This can be achieved with the help of scanf function which is a built-in function in C. This approach is also useful in situations where large array initialization is needed.


#include<stdio.h>

main() {
    int i;
    int sal[5];
    for (i = 0; i < 5; i++) {
        printf(" \n Enter the amount of salary -->[%d]:", i);
        scanf("%d", & sal[i]);
    }
}
 

One Dimensional Array after initialization can be best visualized as follows.

Array

If we don't define the value of any element, the compiler will consider it to be null.

For instance int i[5]={12,52};

This is a valid statement. But it implies:

i[0]=12

i[2]=0

i[1]=52

i[3]=0

i[4]=0

How to access array elements in C

To access elements from an array we can use their indices since we use the same tactics for initialization.

With the help of the scanf function and for loop, we can input values into an array. Similarly, we utilize printf function to print the values accessed from an array using their indices with the help of loops.

Example 1 : How to print an array and reverse it.


#include

int main() {

    int n;
    int arr[100];
    int i;

    printf("Enter the number of elements in array :\n");
    scanf("%d", & n);

    printf("\nEnter the elements in array :\n");
    for (i = 0; i < n; i++) {
        scanf("%d", & arr[i]);
    }

    printf("\nThe array is :\n");
    for (i = 0; i < n; i++) {
        printf("%d\t", arr[i]);
    }

    printf("\n\nThe array in reversed order is:\n");
    for (i = n - 1; i >= 0; i--) {
        printf("%d\t", arr[i]);
    }
    return 0;
}
 

Output:


Enter the number of elements in array :
6

Enter the elements in the array :
10
20
30
40
50
60

The array is :
10      20      30      40      50      60

The array in reversed order is:
60      50      40      30      20      10

Explanation:

In the above program an array, arr[100], of integer data type is declared. This declaration notifies the memory to allocate space for 100 elements. With the help of scanf function, array size has been initialized to variable n. Similarly, elements to the array are initialized. Firstly we displayed the array as it is using the printf function and for loop. Later the reversed array is printed. The only difference lies in for loop declaration.

Example 2 : How to sort elements in a array


include < stdio.h >
    int main() {

        int n;
        int arr[100];
        int i, j, temp;

        printf("Enter the number of elements in array :\n");
        scanf("%d", & n);

        printf("\nEnter the elements in array :\n");
        for (i = 0; i < n; i++) {
            scanf("%d", & arr[i]);
        }

        printf("\nThe unsorted array is :\n");
        for (i = 0; i < n; i++) {
            printf("%d\t", arr[i]);
        }

        for (i = 0; i < n; ++i) {

            for (j = i + 1; j < n; ++j) {

                if (arr[i] > arr[j]) {

                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;

                }

            }

        }

        printf("\nThe sorted array is : \n");
        for (i = 0; i < n; ++i)
            printf("%d\t", arr[i]);

    }
 

Output:


Enter the number of elements in array :
8

Enter the elements in array :
4
44
35
19
76
28
16
46

The unsorted array is :
4       44      35      19      76      28      16      46
The sorted array is :
4       16      19      28      35      44      46      76

The above program illustrates the sorting of elements in an array. Sorting is accomplished by comparing the first element with the second element. If the condition meets then the swapping of elements occurs with the use of a temporary variable, temp and this repeats until all the elements are completely sorted in ascending order. To practice more programs in arrays refer to our sample programs.

What is a two-dimensional (2D) array?

In C programming two-dimensional arrays comprise rows and columns, just like a matrix. So a 2D array can be thought of as an array of arrays.

Declaration of 2D Array

The declaration statement has two consecutive indices, one to represent the number of rows and the other to give the  number of columns, as shown:

data_type array_name [row] [column];
int table [2] [3];

Here, the table is a 2-dimensional array that holds 6 integer values in 2 rows and 3 columns. While declaring two-dimensional arrays both row size and column size must be enclosed in square brackets. The allocation of each element will be as :

2D Array

Initialization of 2D Array:

There are two types of the process by which a 2D array can be initialized.

Compile-time initialization of 2D Array

As previously discussed initialization can be done during declaration and it takes the form

data_type array_name [row] [column]= {value_1st_element,value_2nd_element,3rd.....};

for instance,

int table [2] [3]={
    {10,20,30};
    {40,50,60};      
}

The same can be defined as follows in a single line which is more convenient and easy.

int table[2][3]={10,20,30,40,50,60};

C provides a means to declare an array by leaving the first index blank(row) to be blank whereas it is mandatory to specify the second index (column). The following example shows that in the 2-dimensional array, table, row size is left blank while providing the column size.

int table[][3]={10,20,30,40,50,60};

The compiler does not raise any error as this statement is a valid one and means that any number of rows can be initialized in C. But in case if column size is not mentioned the compiler will raise an error.

Two Dimensional Array after initialization can be best visualized as follows.

Array

Runtime initialization of 2D Array

We can accomplish runtime initialization of a 2 Dimensional array with the help of scanf function. This can be viewed by examining the following program. 


#include<stdio.h>

void main()
{
    int table[3][4];
    int i, j;
    printf("Enter array elements :");
    for(i = 0; i < 3;i++)
    {
        for(j = 0; j < 4; j++)
        {
            scanf("%d", &table[i][j]);
        }
    }
}
 

From the above code snippet, it is pretty clear that to input values into a two-dimensional array we need nested for loop along with scanf function.


// Print an 3 x 3 matrix
#include <stdio.h>

int main()
{
    int i, j, r, c;
    int M[5][5];

    printf("Enter number of rows : ");
    scanf("%d", &r);
    printf("Enter number of columns :");
    scanf("%d", &c);
    printf("\n");
    /* Input data to matrix */
    for (i = 0; i < r; i++)
    {
        for (j = 0; j < c; j++)
        {
            printf("Data in M[%d][%d] = ", i, j);
            scanf("%d", &M[i][j]);
        }
 printf("\n");

    }

    /* Display the matrix */
    for (i = 0; i < r; i++)
    {
        for (j = 0; j < c; j++)
        {
            printf("%d\t", M[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Output:

Enter number of rows : 3
Enter number of columns : 3

Data in M[0][0] = 1
Data in M[0][1] = 2
Data in M[0][2] = 3

Data in M[1][0] = 4
Data in M[1][1] = 5
Data in M[1][2] = 6

Data in M[2][0] = 7
Data in M[2][1] = 8
Data in M[2][2] = 9

1       2       3
4       5       6
7       8       9

This program gives you a clear picture of the 2D array. The array, M[5][5], holds 25 elements with 5 rows and 5 columns. Since the program is to display a 3 x3 matrix, the number of rows and columns is mentioned as 3. Next elements to each position are allocated and finally, the matrix is displayed with the use of printf function and nested for loop.

Multidimensional Array in C

In C programming we can work with arrays having more than two dimensions. a 3-dimensional array takes the syntax

data_type array_name [row][column][pages]= {value_1st_element,value_2nd_element,3rd.....};

For instance,

int arr[10][10][10];

This array will allocate 10X10X10=1000 elements in the memory of the compiler.

The 3D array can be viewed as given below.

Array

Initialization of 3D Array

The initialization of a 3D array is more similar to a 2D array. Observe the below example:


int test[3][3][3] = {
    {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}},
    {{10, 11, 12}, {13, 14, 15}, {16, 17, 18}},
    {{19, 20, 21}, {22, 23, 24}, {25, 26, 27}}
};

This can be visualized as below in the expanded form.

Array

How to pass arrays to function

In C, all types of arrays can be passed through a function to perform specific tasks. Let’s check out how to pass an array element prior to passing arrays to a function.

Passing individual array element to function

Passing individual array elements to function works similar to the way we pass values inside a function.

Here is a simple example of passing an individual element to a function:


#include <stdio.h>
void display_arr(int a);

int main()
{
    int m_arr[] = { 20, 30, 40 };
    display_arr(m_arr[1]);        
    return 0;
}

void display_arr(int a)
{
    printf("%d", a);
}

Output:

30

In this code fragment, the array element at position 1 is only passed to the function,display_arr.

Passing arrays to function

The key point to be remembered always while passing an array is that it only needs to pass the name of the array as the argument in the function, no requirement for square brackets.  

The syntax for passing an array to function is as follows:

functionname(array_name); //passing array

Different ways of function declaration to receive an array as an argument.

To receive an array as an argument we must declare the function in either of these two ways:

  • return_type function(type array_name[SIZE])  ,where size is optional 
  • return_type function(type *arrayname)  

Example 2: Passing one dimensional array to function


#include <stdio.h>
float Average(int marks[]);

int main() {
    int result, marks[] = {48, 38, 45, 46, 40, 36};
    float avg;

    // age array is passed to calculateSum()
    avg = Average(marks);
    printf("Average = %f", avg);
    return 0;
}

float Average(int marks[]) {

  float sum = 0.0;

  for (int i = 0; i < 6; ++i) {
  sum += marks[i];
  }

  return sum/6;
}

 

Output:

Average = 42.166668

In this example, we have passed a one-dimensional array(marks[]) to the function by just mentioning the array_name (marks) alone, without using the square brackets. However, in the function definition, we have mentioned this array_name along with square brackets which tells the compiler that the argument passed is a one-dimensional array.

Similarly, we can pass multidimensional arrays to function.

Return array from a function(Pointer to an array)

Returning an entire array directly through a function is not possible in C. The solution is returning a pointer to the array. But we must declare the data type as static. Otherwise, the compiler will take them as local variables and restrict the program to use the address-value of the array. The architecture of this will be like 

return _type * Function_name() {  
//some statements;   
return array_name;  //array_name as in function definition  
}

We will learn about pointers in the next tutorial in detail.