Write a c program for reversing of an array ( original array element reverse ).

27 Dec 2022 Balmiki Mandal 0 C Programming

Array Reversal Using C: A Practical Example

To write a C program for reversing the elements of an array, we can use the following steps:

  1. Declare an array and initialize it with the elements to be reversed.
  2. Declare two integer variables, i and j, to iterate over the array.
  3. Initialize i to 0 and j to the size of the array minus 1.
  4. While i is less than or equal to j:
    • Swap the elements at indices i and j.
    • Increment i by 1.
    • Decrement j by 1.
  5. Print the reversed array.

Reverse Array in C: A Simple Program

C Programming
#include <stdio.h>

int main() {
  // Declare an array and initialize it with the elements to be reversed.
  int arr[] = {1, 2, 3, 4, 5};

  // Declare two integer variables, i and j, to iterate over the array.
  int i, j;

  // Initialize i to 0 and j to the size of the array minus 1.
  i = 0;
  j = sizeof(arr) / sizeof(arr[0]) - 1;

  // While i is less than or equal to j:
  while (i <= j) {
    // Swap the elements at indices i and j.
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;

    // Increment i by 1.
    i++;

    // Decrement j by 1.
    j--;
  }

  // Print the reversed array.
  printf("The reversed array is: ");
  for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
    printf("%d ", arr[i]);
  }
  printf("\n");

  return 0;
}

Output:

 

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.