c-plus-plus
  1. c-plus-plus-reverse-an-array

C++ Program to Reverse an Array

In this C++ program, we will reverse an array using a loop.

Syntax

#include <iostream>
using namespace std;

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

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

    // Print the reversed array
    for(int i=0; i<arr_size; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}

Example

Input: {1, 2, 3, 4, 5}
Output: {5, 4, 3, 2, 1}

Explanation

In the above program, we have declared an array arr and calculated its size using sizeof() operator. We then run a for loop to swap the elements of the array arr from start to the middle of the array. Finally, we run another for loop to print the reversed array.

Use

Reversing an array is a common task in programming. This program can be used to reverse any given array of integers.

Important Points

  • Array elements can be accessed using their index.
  • The sizeof() operator returns the size of an array in bytes.
  • Swapping two elements in an array requires the use of a temporary variable.

Summary

In summary, this C++ program demonstrates how to reverse an array using a loop. The program is applicable to any array of integers and can be used as a building block for other techniques that require arrays to be reversed.

Published on: