C program to reverse the elements present in a 1-D static array

Source Code

#include <stdio.h>

// utility function to print array elements
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("%d, ", arr[i]);
    }
    printf("\n");
}

int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6};
    int n = 6;

    // initialize two pointers,
    // one at index 0 (i = 0) and
    // another one at last index (j = size of the array - 1)
    int i = 0, j = n - 1;

    printf("Before reverse: ");
    printArray(arr, n);

    while (i < j)
    {
        // swap i-th and j-th elements in the array
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
        i++;
        j--;
    }

    printf("After reverse: ");
    printArray(arr, n);

    return 0;
}

Time Complexity

O(n) where 'n' is the size of the array

Other videos in this series

Back To Home