C program to reverse an array elements

CServer Side ProgrammingProgramming

Suppose we have an array with n elements. We shall have to reverse the elements present in the array and display them. (Do not print them in reverse order, reverse elements in place).

So, if the input is like n = 6 arr = [9, 8, 7, 2, 4, 3], then the output will be [3,4,2,7,8,9]

To solve this, we will follow these steps −

  • for initialize i := 0, when i < quotient of n/2, update (increase i by 1), do:
    • temp := arr[i]
    • arr[i] := arr[n - i - 1]
    • arr[n - i - 1] := temp
  • for initialize i := 0, when i < n, update (increase i by 1), do:
    • display arr[i]

Example

Let us see the following implementation to get better understanding −

#include <stdio.h>
#include <stdlib.h>
#define n 6
int main(){
    int arr[n] = {9, 8, 7, 2, 4, 3};
    int temp;
    for(int i = 0; i<n/2; i++){
        temp = arr[i];
        arr[i] = arr[n-i-1];
        arr[n-i-1] = temp;
    }
    for(int i = 0; i < n; i++){
        printf("%d,", arr[i]);
    }
}

Input

6, 9, 8, 7, 2, 4, 3

Output

3,4,2,7,8,9,
raja
Published on 08-Oct-2021 11:12:44
Advertisements