Program to Reverse an Array in C++

Program explanation:

  • Program declare an integer array of size five, initialize it using for loop.
  •  Pass size and array name to function.
  • Function uses for loop and swap array elements with in it.
  •  A for loop is used to display the final result.

    Following is the program to reverse an array.

#include <iostream>
using namespace std;
void Reverse_Array(int array[],int size)
{   int temp;
    size--;
    int loop_count=0;
    for(int i=0;size>=i;size--,i++)
    {
        loop_count++;// Counts the iterations
        temp=array[i];
        array[i]=array[size];
        array[size]=temp;
    }
    cout<<"Number of Iterations: "<<loop_count<<endl;
}
int main()
{
    int array[5],i;



cout<<"nEnter 5 Integer Values in Arrayn"<<endl;
    for(i=0;i<5;i++)
    {
    cout<<"Enter Value For Index Number array [ "<<i<<" ] -> ";
    cin>>array[i];
    }
    // Calling Reverse Array Values Function
    Reverse_Array(array,5);
    cout << "nReversed Array Values" << endl;
    for(i=0;i<=4;i++)
        {
         cout<<"array ["<<i<<"]"<<"= "<<array[i]<<endl;
        }
    return 0;
}

 

Leave a Reply