Mastering C Arrays: The 3 Key Types Explained

Table of Contents

What is an Array in C?

An array is defined as a sequence of elements of the same type located in adjacent memory addresses. Arrays form the foundation for strings, matrices, data structures and efficient algorithms. It lets you store multiple values under a single variable name.

 

Why Do We Need Arrays?

Imagine you want to store the marks of 100 students. Without arrays, you would need 100 separate variables, which is impractical.

Arrays help you:

  • Store large amounts of data efficiently
  • Process data using loops
  • Write cleaner and shorter code
  • Improve performance and readability

Arrays are essential for:

  • Sorting algorithms
  • Searching algorithms
  • Matrix operations
  • Storing real-world datasets

Declaring Arrays in C

An array can be declared by specifying the data type followed by the array name and its size in a square bracket. Array can have different data types like int, float, char etc.

The syntax for declaring an array is:

data_type array_name[size];

				
					// Example:

int marks[5]={7,9,2,8,0};

float prices[5]={6.5, 0.3,3.1, 1.6, 8.9 };

char vowels[5]={‘a’, ’e’, ‘i’, ’o’, ‘u’}
				
			
Diagram illustrating the syntax for declaring a C array, showing the data type, array name, and size in square brackets, connected to a visual representation of contiguous memory blocks.
Syntax to Storage: Declaring an array like int arr[5]; immediately reserves a specific number of continuous memory blocks for that data type.

Here:

  • int is the data type
  • marks is the array name
  • 5 is the size of the array

The size must be a positive integer.

Consider the example to declare and print the array elements.

				
					#include <stdio.h>

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};

    printf("Array Elements: ");

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

    printf("\n");
    return 0;
}

// Array Elements: 10 20 30 40 50 

				
			
i valueCheck i < 5Access numbers[i]Output
0Truenumbers[0] = 1010
1Truenumbers[1] = 2020
2Truenumbers[2] = 3030
3Truenumbers[3] = 4040
4Truenumbers[4] = 5050
5False--Loop ends

Memory Representation of Arrays

Arrays are stored in contiguous (continuous) memory locations. The operating system allocates a single block of memory to hold all the elements next to each other.  

For example:

When int arr[5]; the system allocates memory for five elements. Each element occupies the same memory size depending on the data type. This is why array access is fast and efficient.

Diagram of C array memory layout showing five integer blocks stored in sequential memory addresses (e.g., 1000, 1004, 1008), demonstrating contiguous allocation.
Contiguous Memory: In an array, elements are neighbors. Notice how the memory addresses increase by a fixed amount for each index.

Initializing Arrays

Arrays can be initialized at the time of declaration. There are three ways.

 

Method 1: Direct Initialization

In the direct initialization method we declare the array size followed by its elements.

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

 

Method 2: Size Inference

In this method we directly declare the array elements without specifying the size. The compiler automatically calculates the size.

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

 

Method 3: Partial Initialization

In the partial Initialization method we define the array size as any number, but only add a few elements the remaining elements are set to 0 by default.

int arr[5] = {1, 2};

 

Accessing Array Elements

Array elements are accessed by using index values. The indexing starts from 0 and continues up to the last element.

syntax: array_name[index];

Diagram of a C array with value boxes labeled with index numbers starting from 0 up to 2. An arrow highlights that index 0 corresponds to the first element.
Zero-Based Indexing: In C, counting always starts at 0. This means the first element is always at arr[0], not arr[1].
				
					#include <stdio.h>

int main() {
    int numbers[3] = {10, 20, 30};
    printf("%d\n", numbers[0]);   // 10
    printf("%d\n", numbers[1]);   // 20
    printf("%d\n", numbers[2]);   //30

    return 0;
}
				
			

Types of Arrays

1. One-Dimensional Arrays

A linear sequence of elements stored in contiguous memory locations. It represents a simple list or a single row of data.

Syntax: type name[size];

Example:

int arr[5];

				
					#include <stdio.h>

int main() {
    int arr[5];

    // Input Loop
    printf("Enter 5 numbers:\n");
    for(int i = 0; i < 5; i++) {
        scanf("%d", &arr[i]);
    }

    // Output Loop
    printf("Array Elements: ");
    for(int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    
    printf("\n");
    return 0;
}

// Enter 5 numbers:
// 4 8 0 7 9
// Array Elements: 4 8 0 7 9 
				
			

2. Two-Dimensional Arrays

An array of arrays. It organizes data into a matrix structure consisting of rows and columns.

type name[rows][cols];

				
					#include <stdio.h>

int main() {
    int matrix[2][3] = {
        {1, 2, 3}, // Row 0
        {4, 5, 6}  // Row 1
    };

    printf("Printing 2D Array:\n");

    // Outer Loop for Rows (0 to 1)
    for (int i = 0; i < 2; i++) {
        
        // Inner Loop for Columns (0 to 2)
        for (int j = 0; j < 3; j++) {
            printf("%d ", matrix[i][j]);
        }
        
        printf("\n"); 
    }

    return 0;
}

// Printing 2D Array:
// 1 2 3 
// 4 5 6 
				
			
i (Row)j (Col)Access matrix[i][j]Output
00matrix[0][0] = 11
01matrix[0][1] = 22
02matrix[0][2] = 33
0-Inner loop ends\n (New Line)
10matrix[1][0] = 44
11matrix[1][1] = 55
12matrix[1][2] = 66
1-Inner loop ends\n (New Line)
2-Outer loop endsStop

Write a C program to add a 2*2 Matrix using Arrays

A 2 * 2 matric can be added by using the formula sum[i][j] = A[i][j] + B[i][j]

				
					#include <stdio.h>

int main() {
    // 1. Declare and Initialize two matrices
    int a[2][2] = {
        {1, 2},
        {3, 4}
    };
    
    int b[2][2] = {
        {5, 6},
        {7, 8}
    };

    int sum[2][2]; // store the result

    printf("Sum Matrix:\n");

    // 2. Loop through rows and columns
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            
            // 3. Add corresponding elements
            sum[i][j] = a[i][j] + b[i][j];
            
            printf("%d ", sum[i][j]);
        }
        printf("\n");
    }

    return 0;
}

// Sum Matrix:
// 6 8 
// 10 12 

				
			
ija[i][j]b[i][j](a + b)Output
00151 + 5 = 66
01262 + 6 = 88
0---Inner loop ends\n (Next Line)
10373 + 7 = 1010
11484 + 8 = 1212
1---Inner loop ends\n (Next Line)

3. Three-Dimensional Arrays

 Arrays with three or more dimensions. A 3-D array is often visualized as a collection of 2-D arrays stacked together (like a cube). Multidimensional arrays are used in Scientific computing, 3D graphics and Complex simulations

Syntax: type name[depth][rows][cols];

				
					#include <stdio.h>

int main() {
    // Declaration: [2] Layers, [2] Rows, [2] Columns
    int arr[2][2][2] = {
        { // Layer 0
            {1, 2},
            {3, 4}
        },
        { // Layer 1
            {5, 6},
            {7, 8}
        }
    };

    // The outer loop selects the layer, the middle loop selects the row and the inner loop selects the column.
    for (int i = 0; i < 2; i++) {
        printf("Layer %d:\n", i);
        
        for (int j = 0; j < 2; j++) {
            for (int k = 0; k < 2; k++) {
                printf("%d ", arr[i][j][k]);
            }
            printf("\n");
        }
        printf("\n");
    }

    return 0;
}

// Layer 0:
// 1 2 
// 3 4 

// Layer 1:
// 5 6 
// 7 8 

				
			
i (Layer)j (Row)k (Col)Access arr[i][j][k]Output
0Layer 0
00011
00122
00-\n (Next Line)
01033
01144
01\n (Next Line)
0\n (End Layer)
1---Layer 1
10055
10166
10--\n (Next Line)
11077
11188
11--\n (Next Line)

Arrays and Functions

Arrays can be passed to functions to perform operations.

Consider the below code to add the numbers.

				
					#include <stdio.h>

// Function to calculate sum
int calculateSum(int arr[], int size) {
    int sum = 0;
    for(int i = 0; i < size; i++) {
        sum += arr[i];
    }
    return sum;
}

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};
    
    // Call the function and store result
    int total = calculateSum(numbers, 5);

    printf("Sum = %d", total);
    
    return 0;
}

// Sum = 15
				
			
iCheck i < 5Access arr[i]Calculation (sum += arr[i])New Sum
--InitializationInitialization0
0True10 + 11
1True21 + 23
2True33 + 36
3True46 + 410
4True510 + 515
5False-Loop Ends15

Applications

  1. Student Marks Management: Arrays store marks of multiple students efficiently under a single variable name.

  2. Sensor Data Collection: Arrays hold continuous sensor readings such as temperature or pressure over time.

  3. Image Processing:  Arrays represent images as grids of pixels arranged in rows and columns.

  4. Inventory Management: Arrays keep track of product quantities and prices in warehouses and stores.

  5. Game Development:  Arrays manage player scores, positions, and game states efficiently.

  6. Traffic Data Analysis: Arrays store hourly or daily vehicle count data for traffic monitoring systems.

  7. Banking Systems:  Arrays store transaction amounts or balances for fast financial calculations.

  8. Scientific Computing:  Arrays store large sets of experimental or simulation data for analysis.

Frequently Asked Questions (FAQs)

1. What is an array in C language?

An array is defined as a sequence of elements of the same type located in adjacent memory addresses. Arrays form the foundation for strings, matrices, data structures and efficient algorithms. It lets you store multiple values under a single variable name.

 

2. How to find the length of an array in C?

In C, the length of an array can be found using the sizeof operator.

int arr[5];
int length = sizeof(arr) / sizeof(arr[0]);

This works only inside the same scope where the array is declared.

 

3. What is a 2D array in C?

A 2D array in C is an array of arrays, commonly used to represent tables or matrices.

int matrix[3][3];

It stores data in rows and columns.

 

4. How to delete a normal array in C?

A normal (static) array in C cannot be deleted manually; it is automatically removed from memory when it goes out of scope (for example when a function ends or a block finishes execution).

void example() {

int arr[5]; // normal array

} // arr is automatically deleted here

 

5. How to reverse an array in C?

				
					#include <stdio.h>

int main() {
    // 1. Declare array and size
    int arr[] = {1, 2, 3, 4, 5};
    int n = 5;

    printf("Original Array: ");
    for(int i = 0; i < n; i++) printf("%d ", arr[i]);
    printf("\n");

    // 2. Reversal Logic
    for(int i = 0; i < n/2; i++) {
        int temp = arr[i];           // Store first element
        arr[i] = arr[n - i - 1];     // Move last element to first
        arr[n - i - 1] = temp;       // Move stored element to last
    }

    printf("Reversed Array: ");
    for(int i = 0; i < n; i++) printf("%d ", arr[i]);
    printf("\n");

    return 0;
}
				
			
iCondition i < 2Swap Pair (arr[i] ↔ arr[4-i])Array After Swap
--Initial State{1, 2, 3, 4, 5}
0TrueSwap arr[0] (1) ↔ arr[4] (5){5, 2, 3, 4, 1}
1TrueSwap arr[1] (2) ↔ arr[3] (4){5, 4, 3, 2, 1}
2FalseLoop Ends{5, 4, 3, 2, 1}