C Online Compiler
Example: Array Reversal using Recursion in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Array Reversal using Recursion #include <stdio.h> // Function to print the array void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } // Function to reverse the array using recursion void reverseArrayRecursive(int arr[], int start, int end) { // Base condition: if start index is greater than or equal to end index, // the sub-array is either empty or has one element, so it's already reversed. if (start >= end) { return; } // Swap elements at start and end int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; // Recursive call for the rest of the array reverseArrayRecursive(arr, start + 1, end - 1); } int main() { // Step 1: Initialize an array int arr[] = {1, 2, 3, 4, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); // Step 2: Print original array printf("Original array: "); printArray(arr, n); // Step 3: Reverse the array using the recursive function reverseArrayRecursive(arr, 0, n - 1); // Step 4: Print reversed array printf("Reversed array (recursive): "); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS