×

C- ARRAY


In this chapter, we will understand about array variables.

What are arrays in c?

Arrays are the collection of same type of data, which is accessed using a common name. The size of the array is fixed. It can store collection of elements that are of same data type. So instead of declaring N number of int variables as follow

int number1, number2, number3;

we can use array to store all N int numbers in a single array variable.


int number[3];

Syntax - Array declaration

data_type array_variable_name[array_size];

How to declare an array ?

Array declaration are very similar to normal variable declaration, except that array variable name is followed by square brackets [].

Look at the declaration of array blow :

//declaring array variable with size 5
int array_variable[5];

Dimensions of array

Array of one dimension are like a list of elements. Each element in array is accessed by their index.

Array of two dimension are like matrix or a table. Each element has a row index and a column index.

Array can also be of more than two dimensions. C puts no restriction on the dimension of array. They are also called multi dimension array.

How to initialize an array ?

Just like any other variables, arrays can be initialized when they are declared. To initialize an array during declaration put the array elements within {} separeted by comma.

int arrayVariable[5] = {10,20,30,40,50};

What is array index ?

Index of array is nothing but the position of the element inside array variable.

All the arrays are consist of contiguous memory locations. Lowest index which is 0 refers to the first element of array, and highest index refers to the last element of array.

Index in array always starts with 0, which means 1 element of the array and index 9 means 10th element in the array

See the below example

//array declaration
int a[5];

//initializing array
a = {10,20,30,40,50};

printf(a[0]); //a[0] - here 0 is the index of first element
printf(a[3]); //a[3] - 3rd index refers to 4th element in the array

Now lets write a small c program for arrays

File name - array_example.c
#include<stdio.h>
void main()
{
        int numbers[4];

        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;
        numbers[3] = 40;

        for(int i=0;i<=4;i++)
        {
            printf("Value of number %d is %d \n", i, numbers[i]);
        }

}
Output
Value of number 0 is 10
Value of number 1 is 20
Value of number 2 is 30
Value of number 3 is 40

In the next chapter, we will learn about Strings.