Problem Statement: Given an array of integers, write a C program to reverse the elements of the array in place.
Note: In-place means without using any additional data structure to store the reverse elements. The original array is updated to contain its elements in reverse order, without creating a new array to hold the reversed elements.
Example:
Input: arr[] = {10, 20, 30, 40, 50}
Output: Reversed array: {50, 40, 30, 20, 10}
Algorithm to Reverse Array Elements.
Program to Reverse the Elements of an Array.
// C program to reverse array elements in-place #include <stdio.h> // Function to swap two elements void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } int main() { int n; printf("Enter the size of the array: "); scanf("%d", &n); int arr[n]; // Input the elements of the array printf("Enter the elements of the array:\n"); for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } int start = 0; int end = n - 1; while (start < end) { swap(&arr[start], &arr[end]); start++; end--; } printf("Reversed array: {"); for (int i = 0; i < n; i++) { printf("%d", arr[i]); if (i < n - 1) { printf(", "); } } printf("}\n"); return 0; }
Enter the size of the array: 5
Enter the elements of the array:
11 10 9 20 8
Reversed array: {8, 20, 9, 10, 11}
Reverse the Elements of the Array Using Recursion.
- Swap the first and last elements of the array.
- Recursively reverse the remaining subarray.
C Program to Reverse Array Using Recursion.
// C code to reverse order of an array using recursive method #include <stdio.h> // Function to swap two elements void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } // Recursive function to reverse an array void reverseArray(int arr[], int start, int end) { // Base case: if the array is empty or has only one element if (start >= end) { return; } // Swap the first and last elements swap(&arr[start], &arr[end]); // Recursively reverse the remaining subarray reverseArray(arr, start + 1, end - 1); } // Function to print an array void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); printf("Original array: "); printArray(arr, n); // Reverse the array reverseArray(arr, 0, n - 1); printf("Reversed array: "); printArray(arr, n); return 0; }
Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1- Time Complexity: O(n)
- Space Complexity: O(1)

Trends is an amazing magazine Blogger theme that is easy to customize and change to fit your needs.