Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
#include <iostream>
using namespace std;

int main() {
        int n;
        cin>>n;
        int a[n];
        for(int i=0; i<n; i++){
            cin>>a[i];
        }
        cout<<a[n-1]<<endl;
        cout<<a[0]<<endl;
     for(int i=n-1; i>=0; i++){
         cout<<a[i];
     }
	return 0;
}


What I have tried:

I am not able to figure out why the second loop is printing some garbage values.
Posted
Updated 29-Sep-22 10:57am

You're starting at the end of the line and incrementing so yeah it will be garbage. You should start at end of line and decrement, as shown in bolded code.

#include <iostream>
using namespace std;

int main() {
        int n;
        cin>>n;
        int a[n];
        for(int i=0; i<n; i++){
            cin>>a[i];
        }
        cout<<a[n-1]<<endl;
        cout<<a[0]<<endl;
     for(int i=n-1; i>=0; i--){
         cout<<a[i];
     }
	return 0;
}
 
Share this answer
 
Comments
CPallini 29-Sep-22 16:50pm    
5.
for(int i=n-1; i>=0; i++){
         cout<<a[i];
     }
Shouldn't that be an i--?
 
Share this answer
 
Comments
CPallini 29-Sep-22 16:50pm    
5.
Because you are counting up, not down:
for(int i=n-1; i>=0; i++){

So you start with the last element and then move to the non-existent one after that.
Try "--" instead of "++"

To be honest, you would have spotted that for yourself in under a minute if you had run that code in the debugger - I'd strongly recommend that you get used to using that, as it's your best friend in development and it's easier to get used to it with simple code like this than with a 100,000 line behemoth later!
 
Share this answer
 
Comments
CPallini 29-Sep-22 16:51pm    
5.
If you really like to increment...
C++
for (auto it = rbegin(a); it != rend(a); ++it)
  cout << *it << " ";
 
Share this answer
 
Comments
jeron1 29-Sep-22 18:25pm    
Nice!

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