Array in C Programming

An array is a collection of homogeneous elements and its following points are:

  • Array have always contiguous memory allocation.
  • An array can stored multiple value with single name.
  • Array name behave like a pointer first location of memory block is allocated through the name of array.
  • An array can initilize only during declaration time no after words.

Need of Array?

We will illustrate this with the help of an example. Let us consider a situation where we have to write a program that accepts the percentages of 100 students and calculates the average percentage.
When we solve this problem, we require 100 different variables to store the percentages and 1 variable to store the average. So when we use an array, if we declare one variable, it stores all the values, and then sorts the numbers of variables.

Types of array

  • 1-D Array
  • 2-D Array
  • Multi-D Array

1-D Array

A 1-D Array in which only one subscript spacification is needed to specify a particular element of the array.

Syntax of 1-D Array
type array_name[size];

where 'type' declares the base type of array which is the type of each element in the array.
The 'array_name' specifies the name of the array.
'size' specifies the no of element in the array.

Example
/* Sum of the elements in the array */
#include<stdio.h>
int main()
{
    int n, sum = 0, i, array[100];
    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);
    printf("Enter the elements in the array\n");
    for(i = 0; i < n; i++)
    {
        scanf("%d", &array[i]);
        sum = sum + array[i];
    }
    printf("Sum = %d", sum);
    return 0;
}

2-D Array

A 2-D array A[m*n] is a collection of m*n elements and it is also known as arrays of array.

Syntax of 2-D Array
type array_name[row][column];

where 'type' declares the base type of array which is the type of each element in the array.
The 'array_name' specifies the name of the array.
'row' specifies the no of rows in the array.
'column' specfies the no of column in the array.

Example
#include<stdio.h>
int main()
{
    int array[100][100];
    int i, j, row, column;
    int sum;
    printf("Enter number of Row=");
    scanf("%d", &row);
    printf("Enter number of Column=");
    scanf("%d", &column);
    printf("Enter arrays elements=\n");
    for (i = 0; i < row; i++)
    {
        for (j = 0; j < column; j++)
        {
            scanf("%d", &array[i][j]);
        }
    }
    /*sum of all elements*/
    /*initializing sum=0*/
    sum = 0;
    for (i = 0; i < row; i++)
    {
        for (j = 0; j < column; j++)
        {
            sum += array[i][j];
        }
    }
    printf("Sum of all elements= %d", sum);
    return 0;
}