C language

Arrays in C Language – Complete Guide with Examples and Code Explanation

🔥 Mastering Arrays in C Language (Complete Guide)

Arrays are one of the most important data structures in C programming. They allow you to store multiple values of the same data type under a single variable name — making your code cleaner, faster, and more efficient.

What is an Array?

An array in C is a collection of elements that are stored in contiguous memory locations. All elements of an array are of the same data type and can be accessed using an index.

✅ Example:


// Declaring and initializing an array in C
#include <stdio.h>
int main() {
    int numbers[5] = {10, 20, 30, 40, 50};

    // Accessing elements using index
    printf("First element: %d\\n", numbers[0]);
    printf("Third element: %d\\n", numbers[2]);

    return 0;
}

Output:


First element: 10
Third element: 30

Why Use Arrays?

  • To store multiple values in a single variable.
  • To easily access and modify elements using indices.
  • To handle large data efficiently using loops.

Types of Arrays in C

✅ 1. One-Dimensional Array

It is a simple list of elements arranged in a single row.


int marks[5] = {90, 85, 75, 88, 92};

✅ 2. Two-Dimensional Array

Used for representing tables, matrices, or grids. It is often referred to as an array of arrays.


// 2D array example
int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};

// Access element
printf("%d", matrix[1][2]);  // Output: 6

✅ 3. Multi-Dimensional Array

In C, you can create arrays with more than two dimensions, though they are less common. For example:


int cube[2][2][2] = {
    {{1, 2}, {3, 4}},
    {{5, 6}, {7, 8}}
};

How to Access Array Elements

You can access elements using an index number. Note that array indices in C start from 0.


int arr[4] = {2, 4, 6, 8};
printf("%d", arr[2]); // Output: 6

Traversing an Array Using Loops

You can use loops like for or while to iterate through all elements of an array.


#include <stdio.h>
int main() {
    int arr[5] = {5, 10, 15, 20, 25};
    for (int i = 0; i < 5; i++) {
        printf("Element %d: %d\\n", i, arr[i]);
    }
    return 0;
}

Memory Representation of an Array

Arrays store data in continuous memory blocks. For example, if arr[0] is stored at address 1000, and each integer occupies 4 bytes, then:

Element Index Address
arr[0] 0 1000
arr[1] 1 1004
arr[2] 2 1008

Common Array Operations

  • Traversal: Visiting each element one by one.
  • Insertion: Adding a new element (if space available).
  • Deletion: Removing an element and shifting remaining ones.
  • Searching: Finding a particular value.
  • Sorting: Arranging elements in ascending/descending order.

✅ Example: Finding Maximum Element


#include <stdio.h>
int main() {
    int arr[5] = {10, 25, 5, 40, 30};
    int max = arr[0];

    for (int i = 1; i < 5; i++) {
        if (arr[i] > max)
            max = arr[i];
    }

    printf("Maximum element: %d", max);
    return 0;
}

Output: Maximum element: 40

Common Array Operations in C (With Step-by-Step Explanation)

Arrays are not just for storing data — they are also used to manipulate and manage data efficiently. The four most common operations you’ll perform on arrays are Insertion, Deletion, Searching, and Sorting. Let’s explore each one with clear examples and explanations.

✅ 1. Insertion – Adding a New Element

Insertion means adding a new element at a specific position in an array. Since arrays have a fixed size and contiguous memory allocation, inserting a new element usually requires shifting existing elements to make room for it.

Example 1: Inserting an Element at the End


#include <stdio.h>
int main() {
    int arr[10] = {1, 2, 3, 4, 5};
    int n = 5; // current size
    int newElement = 6;

    arr[n] = newElement;
    n++;

    printf("After insertion: ");
    for(int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}

Explanation:

  • The array has 5 elements initially: 1, 2, 3, 4, 5
  • We simply add the new element 6 at position arr[5] (the next available index)
  • Since we had space in the array, no shifting was needed.
  • Output: 1 2 3 4 5 6

Example 2: Inserting an Element in the Middle


#include <stdio.h>
int main() {
    int arr[10] = {10, 20, 30, 40, 50};
    int n = 5;
    int pos = 2; // insert after 2nd index
    int newElement = 25;

    for(int i = n; i > pos; i--)
        arr[i] = arr[i-1]; // shift right

    arr[pos] = newElement;
    n++;

    printf("After insertion: ");
    for(int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}

Explanation:

  • Initial array: 10, 20, 30, 40, 50
  • We insert 25 at position 2 (third element)
  • To make space, elements after position 2 are shifted one step right
  • Final array: 10, 20, 25, 30, 40, 50

✅ 2. Deletion – Removing an Element

Deletion means removing an element from a specific index or by value. After deleting, you must shift the remaining elements to close the gap created by the removed element.

Example 1: Deleting Element by Index


#include <stdio.h>
int main() {
    int arr[6] = {10, 20, 30, 40, 50, 60};
    int n = 6, pos = 2;

    for(int i = pos; i < n-1; i++)
        arr[i] = arr[i+1]; // shift left
    n--;

    printf("After deletion: ");
    for(int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}

Explanation:

  • Original array: 10, 20, 30, 40, 50, 60
  • We delete the element at index 2 (value 30)
  • All elements after index 2 are shifted left
  • Final array: 10, 20, 40, 50, 60

Example 2: Deleting Element by Value


#include <stdio.h>
int main() {
    int arr[6] = {5, 10, 15, 20, 25, 30};
    int n = 6, value = 20, pos = -1;

    for(int i = 0; i < n; i++) {
        if(arr[i] == value) {
            pos = i;
            break;
        }
    }

    if(pos != -1) {
        for(int i = pos; i < n-1; i++)
            arr[i] = arr[i+1];
        n--;
    }

    printf("After deletion: ");
    for(int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}

Explanation:

  • We first find the position of the value 20.
  • Once found, we shift all elements after it one step left.
  • If the value doesn’t exist, we simply skip deletion.
  • Output: 5 10 15 25 30

✅ 3. Searching – Finding a Particular Value

Searching is the process of finding whether a specific element exists in an array. There are two main techniques: Linear Search and Binary Search.

Example 1: Linear Search


#include <stdio.h>
int main() {
    int arr[5] = {10, 25, 30, 45, 60};
    int n = 5, value = 45, found = 0;

    for(int i = 0; i < n; i++) {
        if(arr[i] == value) {
            printf("Element found at index %d", i);
            found = 1;
            break;
        }
    }
    if(!found)
        printf("Element not found");
    return 0;
}

Explanation:

  • Linear search checks each element one by one.
  • If it finds a match, it prints the index and stops.
  • Best for small arrays or unsorted data.

Example 2: Binary Search (Requires Sorted Array)


#include <stdio.h>
int main() {
    int arr[] = {5, 10, 15, 20, 25, 30};
    int n = 6, value = 20;
    int low = 0, high = n - 1, mid, found = 0;

    while(low <= high) {
        mid = (low + high) / 2;
        if(arr[mid] == value) {
            printf("Element found at index %d", mid);
            found = 1;
            break;
        }
        else if(arr[mid] < value)
            low = mid + 1;
        else
            high = mid - 1;
    }

    if(!found)
        printf("Element not found");
    return 0;
}

Explanation:

  • Binary Search divides the array into halves repeatedly.
  • Compare the middle element with the target value.
  • If target is greater, search the right half; otherwise, search the left half.
  • It’s much faster than linear search for sorted arrays.

✅ 4. Sorting – Arranging Elements

Sorting means arranging array elements in ascending or descending order. Sorting is important in data organization, searching, and optimization. Here are two simple methods.

Example 1: Bubble Sort (Ascending Order)


#include <stdio.h>
int main() {
    int arr[5] = {30, 10, 50, 20, 40};
    int n = 5;

    for(int i = 0; i < n-1; i++) {
        for(int j = 0; j < n-i-1; j++) {
            if(arr[j] > arr[j+1]) {
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }

    printf("After sorting: ");
    for(int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}

Explanation:

  • Compares adjacent elements and swaps them if they are in the wrong order.
  • After each pass, the largest element moves to the end.
  • Output: 10 20 30 40 50

Example 2: Selection Sort (Descending Order)


#include <stdio.h>
int main() {
    int arr[5] = {12, 35, 1, 10, 34};
    int n = 5;

    for(int i = 0; i < n-1; i++) {
        int max = i;
        for(int j = i+1; j < n; j++) {
            if(arr[j] > arr[max])
                max = j;
        }
        int temp = arr[i];
        arr[i] = arr[max];
        arr[max] = temp;
    }

    printf("After sorting (descending): ");
    for(int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}

Explanation:

  • Selection sort finds the maximum (or minimum) element in each pass and places it at the correct position.
  • This version arranges elements in descending order.
  • Output: 35 34 12 10 1

🎯 Summary

  • Insertion: Add new element, may require shifting.
  • Deletion: Remove element, shift left to fill gap.
  • Searching: Find element (linear or binary).
  • Sorting: Arrange in ascending/descending order.

Understanding these operations builds the foundation for learning advanced data structures like linked lists, stacks, and queues.

Limitations of Arrays

  • Fixed size — cannot grow or shrink dynamically.
  • All elements must be of the same data type.
  • Insertion and deletion operations can be costly (require shifting).

Conclusion

Arrays are the backbone of data structures in C. They help in organizing and managing data efficiently. Once you master arrays, you can easily move on to advanced topics like pointers, strings, and dynamic memory allocation.

🧩 Exercises on Arrays in C

Practice is the key to mastering arrays! Try solving the following exercises, starting from basic to medium-level problems. Each exercise will help you apply the concepts learned above.

✅ Level 1: Basic Understanding

  1. Print Array Elements
    Write a program to declare an array of 5 integers, take input from the user, and print all the elements using a loop.
  2. Sum of Array Elements
    Create a program that finds the sum of all elements in an integer array of size 10.
  3. Find the Maximum Element
    Write a C program to find and display the largest number in an array.

✅ Level 2: Logic and Conditionals

  1. Count Even and Odd Numbers
    Accept 10 numbers in an array and count how many of them are even and how many are odd.
  2. Reverse an Array
    Take 5 elements from the user and print them in reverse order without using an extra array.
  3. Search an Element
    Write a program to search for a given number in an array. If found, print its index; otherwise, display “Element not found”.

✅ Level 3: Moderate Practice

  1. Insert an Element at a Specific Position
    Write a C program to insert a new number into an array at a specified position (without overwriting existing elements).
  2. Delete an Element from an Array
    Create a program that deletes an element from an array based on the given position and shifts the remaining elements.
  3. Sort Array in Ascending Order
    Accept 5 integers in an array and sort them in ascending order using the Bubble Sort technique.
  4. Merge Two Arrays
    Write a program to merge two arrays into a third array, then print the combined array.

Bonus Tip: Try solving these problems first on paper, then write and test them in your C compiler. This helps you understand both logic and syntax!

Leave a Reply

Your email address will not be published. Required fields are marked *