Click here to Skip to main content
15,884,177 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C++
#include <iostream>
using namespace std;

void revarray(int a[],int start,int end)
{
    int total=end;
    int tmp;
    while(start<end)
    {
       tmp=a[start];
       a[start]=a[end];
       a[end]=tmp;
       start++;
       end--;
    }
    for(int i=0;i<=total;i++)
    {
        cout<<a[i]<<" ";
    }
}
int main()
{
   int n;
   cout<<"ENter range of a array:";
   cin>>n;
   int a[n],i;
   cout<<"Enter array elmensts:";
   for(i=0;i<n;i++)
   {
       cin>>a[i];
   }
   revarray(a,0,n);
}


What I have tried:

C++
#include <iostream>
using namespace std;

void revarray(int a[],int start,int end)
{
    int total=end;
    int tmp;
    while(start<end)
    {
       tmp=a[start];
       a[start]=a[end];
       a[end]=tmp;
       start++;
       end--;
    }
    for(int i=0;i<=total;i++)
    {
        cout<<a[i]<<" ";
    }
}
int main()
{
   int n;
   cout<<"ENter range of a array:";
   cin>>n;
   int a[n],i;
   cout<<"Enter array elmensts:";
   for(i=0;i<n;i++)
   {
       cin>>a[i];
   }
   revarray(a,0,n);
}
Posted
Updated 7-Dec-20 10:45am
v2

C++
revarray(a,0,n); // change to n - 1

The last element of an array is at offset n - 1, not n.
 
Share this answer
 
Comments
CPallini 7-Dec-20 16:23pm    
5.
Array elements are numbered 0 through n-1. So if you have an array of 10 elements, they are numbered 0 through 9. You have to keep that in mind when you write your code.
 
Share this answer
 
Comments
CPallini 7-Dec-20 16:24pm    
5.
Probably you are doing it as an exercise on C-like arrays.
Anyway I make you aware that C++ provides containers and iterators
C++
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;

int main()
{
  int n;
  cout << "please enter the number of the array elements\n";
  cin >> n;
  vector <int> v(n,0);
  cout << "now, please, enter the array elements\n";
  for ( auto & x : v)
    cin >> x;
  for ( auto it = rbegin(v); it != rend(v); ++it)
    cout << (*it) << " ";
  cout << endl;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900