C++ Program to Reverse an Array

In this we discussed about how to find the reverse of an array  with some approaches and you can also do with more approaches 

the below points mentions we discussed in this article


  • Question
  • sample input
  • Logic
  • solution with loop
  • solution using function
  • video explanation



Question- 

 wap in  C++  to Reverse an Array


sample input 

enter the range - 4

2 4 6 3

After reversing the elements are

3 6 4 2

Logic to solve

  • Take an array of some integers then take a variable ( n )  for taking the input how many data the user want to enter then run a for loop to taking the inputs . 
  • Again run another for loop but this time make the condition till n/2 because we want to swap this time like from last value to first and the process continue till the half so we take n/2.
  • Take a temp variable and swap the values .
  • Then again run a for loop to displaying the array after reversing.


C++ Program to reverse an array


solve using for loop


Source Code

#include<iostream>

using namespace std;

int main()

{

    int arr[10],n;


    //to taking the inputs for array

    cout<<"Enter the range of array :"<<endl;

    cin>>n;

    for (int i = 0; i < n; i++)

    {

        cout<<"Enter the data no. "<<i+1<<" :";

        cin>>arr[i];

    }

    

    //to reverse the array

    for (int i = 0; i < n/2; i++)

    {

        int temp;

        temp=arr[i];

        arr[i]=arr[n-1-i]; //arr[n-1-i] is for swapping from last to reverse

        arr[n-1-i]=temp;

    }

    //to show the array 


    cout<<"After reversing the array :\n";

    for (int i = 0; i < n; i++)

    {

        cout<<arr[i]<<" ";

    }

    return 0;

}


VIDEO EXPLANATIONS




solve using functions


source code

#include<iostream>

using namespace std;


//This function is to reverse the array

void reversearr(int arr[],int n)  //function definitions

{

  for (int i = 0; i < n/2; i++)

    {

        int temp;

        temp=arr[i];

        arr[i]=arr[n-1-i]; //arr[n-1-i] is for swapping from last to reverse

        arr[n-1-i]=temp;

    }

}


//this function is to display the array

void display(int arr[],int n)

{

   cout<<"After reversing the array :\n";

    for (int i = 0; i < n; i++)

    {

        cout<<arr[i]<<" ";

    }

}

int main()

{

    int arr[10],n;


    //to taking the inputs for array

    cout<<"Enter the range of array :"<<endl;

    cin>>n;

    for (int i = 0; i < n; i++)

    {

        cout<<"Enter the data no. "<<i+1<<" :";

        cin>>arr[i];

    }

    reversearr(arr,n); //function call

    display(arr,n); 

    return 0;

}

All array questions for practice in our website must visit 


Also check Out


Also check Out Projects for Resume

    click here

Projects on C++


Projects on C


Problems On C


Problems On C++





FEEDBACK

if still have you any doubts please comment below  we try to solve that






Post a Comment

Please do not spam in comment