Arrays in C

An array is a collection of similar data elements stored in contiguous memory locations under a single name. Instead of storing multiple variables, arrays allow you to store multiple values in one variable.


1. Declaration of Array

Syntax

data_type array_name[size];

Example

int marks[5];

This creates an array that can store 5 integer values.


2. Initialization of Array

Method 1: At declaration

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

Method 2: Without size

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

Method 3: Individual assignment

int marks[3];
marks[0] = 10;
marks[1] = 20;
marks[2] = 30;

3. Accessing Array Elements

Array index starts from 0.

marks[0]  // first elementmarks[1]  // second element

Example Program: Array Input & Output

#include <stdio.h>

int main()
{
    int i;
    int marks[5];

    printf("Enter 5 marks:\n");

    for(i = 0; i < 5; i++)
    {
        scanf("%d", &marks[i]);
    }

    printf("Marks are:\n");

    for(i = 0; i < 5; i++)
    {
        printf("%d\n", marks[i]);
    }

    return 0;
}

4. Memory Representation

Array elements are stored in continuous memory blocks.

Example:

marks[0] -> 10
marks[1] -> 20
marks[2] -> 30

5. Types of Arrays

1. One-Dimensional Array

Stores a single row of elements.

int arr[5];

Example:

int numbers[5] = {1, 2, 3, 4, 5};

2. Two-Dimensional Array (Matrix)

Used to store data in rows and columns.

Syntax

int arr[rows][columns];

Example

#include <stdio.h>

int main()
{
    int i, j;
    int matrix[2][3] = {{1,2,3}, {4,5,6}};

    for(i = 0; i < 2; i++)
    {
        for(j = 0; j < 3; j++)
        {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Output

1 2 3
4 5 6

3. Multi-Dimensional Array

Array with more than 2 dimensions.

int arr[3][3][3];

6. Example: Find Sum of Array Elements

#include <stdio.h>

int main()
{
    int i, sum = 0;
    int arr[5] = {10, 20, 30, 40, 50};

    for(i = 0; i < 5; i++)
    {
        sum = sum + arr[i];
    }

    printf("Sum = %d", sum);

    return 0;
}

Output

Sum = 150

7. Advantages of Arrays

  • Store multiple values using a single variable name
  • Easy to access data using index
  • Useful for sorting and searching algorithms
  • Reduces code complexity

8. Disadvantages of Arrays

  • Fixed size (cannot grow dynamically)
  • Only stores same data type
  • Insertion and deletion are difficult

9. Summary

  • An array stores multiple values of the same type.
  • Index starts from 0.
  • Arrays can be 1D, 2D, or multi-dimensional.
  • They are stored in continuous memory locations.
  • Very useful in loops, matrices, and data processing.

Related Posts