OverIQ.com

C Program to reverse the elements of an array

Last updated on September 23, 2020


The following is a C Program to reverse the elements of an array:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**********************************************
 Program to reverse the elements of an array 
 **********************************************/

#include<stdio.h> // include stdio.h library
#define MAX 5

int main(void)
{    
    int arr[MAX] = {10, 20, 30, 40, 50},
            i, j, tmp;

    i = 0;
    j = MAX - 1; // assign the last valid index 

    while(i < j)
    {
        // swap the elements
        tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp; 

        i++;  
        j--;
    }

    //  print the reversed array
    for(int k = 0; k < MAX; k++)
    {
        printf("%d ", arr[k]);
    }

    return 0; // return 0 to operating system
}

Try it now

Expected Output:

50 40 30 20 10

How it works #

To reverse the elements of an array, we swap the first element of the array with the last element, the second element with the second last element, and so on. We keep repeating this procedure until we reach halfway through the array.

The following figure demonstrates the process in action: