Signup/Sign In

Arrays in C

In C language, arrays are referred to as structured data types. An array is defined as finite ordered collection of homogenous data, stored in contiguous memory locations.

Here the words,

  • finite means data range must be defined.
  • ordered means data must be stored in continuous memory addresses.
  • homogenous means data must be of similar data type.

Some uses of Arrays in C

Following are some usecases where using an array will make things simpler:

  • to store list of Employee or Student names,
  • to store marks of students,
  • or to store list of numbers or characters etc.

Since arrays provide an easy way to represent data, it is classified amongst the data structures in C. Other data structures in c are structure, lists, queues, trees etc.

Array is a linear data structure which means that the elements in an array are stored in a continuous manner in the memory. This makes accessing the elements easier. Array elements are indexed in an order, starting from 0 to n-1, where n is the size of the array.

Suppose we have a classroom of 50 students. Our array will consist of 50 elements with indexes from 0 to 49, where one place will be there for every student's data.

Arrays can be single or multi dimensional. The number of dimensions in an array is equal to the number of indexing. A 2-D array (also called a matrix) has two indexes(one for row and other for column) and so on.

Arrays make our work easy because instead of declaring 100 variables, we can declare an array of size 100.

Advantages of Arrays

  • In one go, we can initialise storage for more than one value. Because you can create an array of 10, 100 or 1000 values.
  • They make accessing elements easier by providing random access. By random access we mean you can directly access any element in an array if you know its index.
  • Sorting and searching operations are easy on arrays.

Disadvantages of Arrays

  • Due to its fixed size, we cannot increase the size of an array during runtime. That means once you have created an array, then it's size cannot be changed.
  • Insertion and deletion of elements can be costly, in terms of time taken.

Declaring Arrays in C

Like any other variable, arrays must be declared(created) before they are used. General form of array declaration is,

data-type variable-name[size];

Let's see some code example real quick,

/* Example of array declaration */
char a[5];    /* char type value array */
float ar[9];  /* float type value array */
int arr[10];  /* int type value array */

array declaraction in c

In the code above, in the first line, char is the data type, a is the name of array and 5 is the size.

In the next line, float is the data type, ar is the name of the array and size of array is 9.

And in the last line of code, int is the data types, and arr is the name of the array and 10 is the size of array. It means array arr can only contain 10 elements of int type.

The index of an array starts from 0 to size-1 i.e first element of any array will be stored at arr[0] address and the last element will be at arr[size - 1].


Initialization of Array in C

After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random value). An array can be initialized at either compile time or at runtime. That means, either we can provide values to the array in the code itself, or we can add user input value into the array.

Compile time Array initialization in C

Compile time initialization of array means we provide the value for the array in the code, when we create the array,

data-type array-name[size] = { list of values };

Let's see a few simple examples,

/* Here are a few examples */ int marks[4] = { 67, 87, 56, 77 }; // integer array initialization float area[5] = { 23.4, 6.8, 5.5 }; // float array initialization int marks[4] = { 67, 87, 56, 77, 59 }; // Compile time error

One important thing to remember is that when you will give more values(array elements) than the declared array size than the compiler will give an error.

#include<stdio.h>

void main()
{
    int i;
    int arr[] = {2, 3, 4};      // Compile time array initialization
    for(i = 0 ; i < 3 ; i++) 
    {
        printf("%d\t",arr[i]);
    }
}

2 3 4

Runtime Array initialization in C

An array can also be initialized at runtime using scanf() function. This approach is usually used for initializing large arrays, or to initialize arrays with user specified values.

To input elements in an array, we can use a for loop or insert elements at a specific index.

For example, to insert element at specific index,

scanf("%d", &arr[3]); // will insert element at index 3, i.e. 4th position

Let's suppose we have an array Arr of 10 elements of type int.

To insert elements at each index,

for(int i = 0; i < 10; i++)
    Arr[i] = i;

Here i refers to the index of the elements, starting from 0 and ending at 9 which is less than 10. In each element, we store the value of its index.

To insert elements at each index according to user, we can do the following,

for(int i = 0; i < 10; i++)
    scanf("%d", &Arr[i]);

To insert elements at alternate index,

for(int i = 0; i < 10; i+=2)
    scanf("%d", &Arr[i]);

Notice that in the above example, we are incrementing i by 2 each time, i+=2 means i = i + 2. So we input only even indexed elements like Arrr[0], Arr[2], and so on.

Accessing Array elements in C

We already know how to access array elements. Yes, it is using the indexes. So let's see a few examples where we will print entire arrays or some specific values, etc.

To print all elements,

for(int i = 0; i < 10; i++)
    printf("%d", Arr[i]);

To access and print elements at specified index,

printf("%d", Arr[0]); //prints first element of the array
printf("%d", Arr[5]); //prints sixth element of the array

To access elements at alternate index,

for(int i = 0; i < 10; i+=2)
    printf("%d", Arr[i]);

If we try to access elements, on index which is more than the size of an array or less than 0, we won't get an error but we will get wrong output (some random garbage value).

Array Programs in C

Let's see a few basic programs where we will be using arrays.

1. Calculate sum of all array elements

The following program is used to calculate the sum of all elements of an array.

#include<stdio.h>
void main(){

    int arr[5];
    printf("Enter array elements:"");
    for(int i = 0; i < 5; i++)
        scanf("%d", &arr[i]);

    printf("Array elements are:"");
    for(int i = 0; i < 5; i++)
        printf("%d ", arr[i]);
    int sum = 0;
    for(int i = 0; i < 5; i++)
        sum += arr[i];
    printf("Sum =%d", sum);
}

 


Enter array elements:3 2 4 1 5
Array elements are:3 2 4 1 5
Sum =15

2. Copy data from one array to another

This program will copy all the elements of one array into another, we use a for loop.

#include <stdio.h>
int main()
{
    float arr1[5] = {1.5, 2.1, 3.7, 4.2, 5.5}, arr2[5];
    for(int i = 0; i < 5; i++)
        arr2[i] = arr1[i];

    for(int i = 0; i < 5; i++)
        printf("%d ", arr2[i]);
    return 0;
}


1.5 2.1 3.7 4.2 5.5

If you were thinking that we can assign values from an array to another using an assignment operator, like we do in variables, NO you can't.

Array1 = Array2;  // error

We can also create boolean arrays in C. Unlike other data types, boolean arrays have only two values, i.e., true(1) and false(0).

Please note that in order to use bool, we use <stdbool.h> header file in our code. Also, there is no format specifier for bool in C. We use %d for input/output.

Suppose a teacher wants to store the data of assignment submission of her class of 5 students. To do so, she makes use of a boolean array where she inputs "yes" or "no" corresponding to the respective roll numbers. Following is the code for this example.

#include <stdio.h>
#include <stdbool.h>
int main()
{

    bool submitted[5] = {'0', '1', '1', '0', '1'};

    printf("Submission details are:\n");
    for(int i = 0; i < 5; i++)
        printf("%d : %d\n",i + 1, submitted[i]);
    return 0;
}


1 : 0
2 : 1
3 : 1
4 : 0
5 : 1


Two dimensional Arrays

C language supports multidimensional arrays too. The simplest form of a multidimensional array is the two-dimensional array. Here, we have a row index and a column index. Both the row's and column's index begins from 0.

Just like a single-dimensional array, we can do Compile time initialization of two dimensional arrays or runtime initialization of two dimensional arrays.

Two-dimensional arrays are declared as follows,

data-type array-name[row-size][column-size]

Please note and remember, the first [] holds row count and second [] holds column count.

double arr[5][5];
int a[3][4];

two dimensional array in c

Compile-time initialization of a two dimensional Array

If you want to do Compile time initialization of two dimensional array, then here is an example,

int arr[][3] = {
    {0,0,0},
    {1,1,1}
};

char a[][2] = {
{'a', 'b'},
{'c', 'd'}
};

Note: We have not assigned any row value to our arrays in the above example. It means we can initialize any number of rows. But, we must always specify number of columns, else it will give a compile time error. Here, a 2*3 multi-dimensional matrix is created.

Let's see a few more examples,

int arr1[2][2] = {1, 2, 3, 4}; // equivalent to {{1, 2},{3, 4}}
int arr2[2][3] = {1, 2, 3, 4}; // equivalent to {{1, 2, 3},{4}}
int arr3[2][4] = {1, 2, 3, 4}; // equivalent to {{1,2,3,4}}

As you can see in the example above, first the values are stored in columns, and then if there is any extra value, it goes to next row.

Runtime initialization of a two dimensional Array

Now let's see how we can initialize a two dimensional array at runtime.

#include<stdio.h>
void main()
{
    int arr[3][4];
    int i, j, k;
    printf("Enter array elements:\n");
    for(i = 0; i < 3;i++)
    {
        for(j = 0; j < 4; j++)
        {
            scanf("%d", &arr[i][j]);
        }
    }
    for(i = 0; i < 3; i++)
    {
        for(j = 0; j < 4; j++)
        {
           printf("%d", arr[i][j]);
        }
    }
}


Enter array elements:
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5 6 7 8 9 10 11 12

Using the first for loop, we first access the row of the matrix(2D array) and in that particular row, we traverse each column using the inner for loop.

Understanding how we access elements in a 2-D array can be tricky. Let us suppose we have an array arr[2][3] with 2 rows and 3 columns.

We use i to access the rows of our matrix. In the outer loop(line 7), we initialize i as 0 which means we are accessing the first row currently. Now in this for loop, we have an inner loop(line 9) which iterates over j and is used to access columns. So for i = 0 (the first row), we traverse across j (from 0 to 2). When we enter the inner loop, we have already fixed the value of i as 0 and now we iterate over j and keep incrementing the values.

So, we have arr[0][0], then we increment j by 1 to access arr[0][1], then arr[0][2].

On line 12, we come out of the inner loop when j = number of columns. We check the condition of the outer loop. If i = number of rows, we exit the loop otherwise we enter it again with an incremented i. In the similar way, we access all elements of a matrix.

To print the elements of different rows in different lines,

for(int i = 0; i < 3; i++)
{
    for(int j = 0; j < 4; j++)
    {
         printf("%d", arr[i][j]);
    }
    printf(“\n”);
}

Using 2D Array in Program in C

Let's suppose we want to calculate the total marks of all students in a class. We can do it by using a matrix. Here, the number of rows will represent the number of students and the number of columns will represent the subjects.

So first we'll input marks for the first student in all 3 subjects, then the second and so on. We'll sum the marks rowwise and store it in a separate array.

#include <stdio.h>
int main()
{

     float marks[2][3], total[2];

     for(int i = 0; i < 2; i++) {
         for(int j = 0; j < 3; j++){
              scanf("%f", &marks[i][j]);
         }  
     }

     for(int i = 0; i < 2; i++) {
         float sum = 0;
         for(int j = 0; j < 3; j++){
              sum += marks[i][j];
         }
         total[i] = sum;
     }

     for(int i = 0; i < 2; i++)
         printf("%d : %f\n", i + 1, total[i]);

     return 0;
}


1.2 2.3 4.5 6.7 7.8
1 : 8.000000
2 : 17.900002

Similarly, we can reverse an array, find out the maximum and minimum in an array and perform many other operations.

If you want to learn about string and char arrays, click here.

You can find more programs for array in C to practice.