C program to find reverse of an array

Category: C Program

Learn how to write a C program to find the reverse of an array. This article provides a detailed explanation and sample code for reversing an array using a simple iterative approach.

Reversing an array is a common task in C programming, often required in various applications such as data manipulation, algorithm implementation, and problem-solving. This article will guide you through writing a C program to find the reverse of an array, providing a detailed explanation and sample code.

Steps to Reverse an Array

To reverse an array, we can follow these steps:

  1. Input the Array: Read the array elements from the user.
  2. Reverse the Array: Swap the elements from the beginning and the end of the array, moving towards the center.
  3. Print the Result: Output the reversed array to the console.

Write a C Program to Find the Reverse of an Array

#include <stdio.h>

int main() {
    int size;

    // Input size and elements of the array
    printf("Enter the size of the array: ");
    scanf("%d", &size);
    int arr[size];
    printf("Enter %d elements  -\n", size);
    for (int i = 0; i < size; i++) {
        scanf("%d", &arr[i]);
    }

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

    // Print the reversed array
    printf("Reversed array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

Output

Enter the size of the array: 5
Enter 5 elements  -
1
2
3
4
5
Reversed array: 5 4 3 2 1

Explanation

  1. Input the Array: The user inputs the size of the array and its elements.
  2. Reverse the Array: The program uses a loop to iterate from the beginning to the middle of the array. During each iteration, it swaps the current element with the corresponding element from the end of the array.
  3. Print the Result: The program prints the elements of the reversed array.

Detailed Steps

  • Step 1: Input the Array
    • The program prompts the user to enter the size of the array.
    • The user inputs the array elements.
  • Step 2: Reverse the Array
    • A loop runs from the start of the array to its middle (size/2).
    • During each iteration of the loop, the element at the current index is swapped with the element at the corresponding index from the end of the array.
    • This process is repeated until all elements are reversed.
  • Step 3: Print the Result
    • The program prints the elements of the array after it has been reversed.

Recommended Posts