Home > other >  What is wrong in this program //trying to reverse an array?
What is wrong in this program //trying to reverse an array?

Time:08-09

I am trying to create a program to reverse an array by creating a temporary array defined within a fucntion and then copying the elements of the from the end of array to the start of the temporary array.

#include<iostream>
using namespace std;

void reverse(int arr[])
{
    int revarray[10];
    for(int i=0;i<10;i  )
       for(int j=9;j>=0;j--)
       {
          revarray[j]=arr[i]; 
       }
    for(int k=0;k<10;k  )
    {
        cout<<revarray1[k]<<" ";
    }
}

int main()
{
   int arr[10];
   cout<<"Enter the elements of array"<<endl;
    for(int i=0;i<10;i  )
    {
        cin>>arr[i];
    }
    reverse(arr);   
}

This is the output that i am getting

CodePudding user response:

In these nested for loops

for(int i=0;i<10;i  )
   for(int j=9;j>=0;j--)
   {
      revarray[j]=arr[i]; 
   }

you are setting all elements of the array revarray with values of the array arr within the inner for loop in each iteration of the outer for loop. As a result after the loops all elements of the array revarray contain the value arr[9].

In any case the function is wrong because it uses the magic number 10. So it may not be called for arrays with other numbers of elements.

If you want to reverse an array then the function can look for example the following way as shown in the demonstration program below.

#include <iostream>
#include <utility>

void reverse( int arr[], size_t n )
{
    for ( size_t i = 0; i < n / 2; i   )
    {
        std::swap( arr[i], arr[n - i - 1] );
    }
}

int main()
{
    const size_t N = 10;    
    int arr[N];

    std::cout << "Enter the elements of array" << std::endl;

    for ( size_t i = 0; i < N; i   )
    {
        std::cin >> arr[i];
    }

    reverse( arr, N );   

    for ( const auto &item : arr )
    {
        std::cout << item << ' ';
    }
    std::cout << std::endl;
}

Pay attention to that there is standard algorithm std::reverse declared in header <algorithm> that can be used with arrays.

In this case to reverse an array you could write

#include <iterator>
#include <algorithm>

//...

std::reverse( std::begin( arr ), std::end( arr ) );
  • Related