Write a c program to reverse the elements of a given array

28 Dec 2022 Balmiki Mandal 0 C Programming

Array Reversal in C: Step-by-Step Guide

To reverse the elements of a given array in C, we can use the following steps:

  1. Declare an integer variable i to iterate over the array.
  2. Initialize i to 0.
  3. While i is less than the length of the array:
    • Swap the elements at indices i and length - i - 1.
    • Increment i by 1.
  4. Return the array.

The following code shows how to implement these steps in C:

C programming
void reverseArray(int arr[], int length) {
  int i;

  for (i = 0; i < length / 2; i++) {
    int temp = arr[i];
    arr[i] = arr[length - i - 1];
    arr[length - i - 1] = temp;
  }
}

int main() {
  int arr[] = {1, 2, 3, 4, 5};
  int length = sizeof(arr) / sizeof(arr[0]);

  reverseArray(arr, length);

  for (int i = 0; i < length; 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.