+ 2
Reversing Numbers
Hi everyone ! I’ve written a code to reverse numbers which are entered by the user (i.e: the user enters 1234 the output will be 4321) But the code only reverse 6 numbers. 123456 ===> 654321 I can’t find the problem #include <iostream> using namespace std; int main() { int i=1; int x[i],z; cout<<"Enter the number of the numbers"<<endl; cin>>z; cout<<"Enter the first number"<<endl; cin>>x[i]; while (i<z){ cout<<"Enter the next number"<<endl; i++; cin>>x[i]; } while (i>=1){ cout<<x[i]; i--; } return 0; }
10 Respuestas
+ 5
#include<iostream>
using namespace std;
int main() {
int n,t,r,rev=0;
cout<<"Enter any number : ";
cin>>n;
t=n;
while(t>0) {
r=t%10;
t=t/10;
rev=rev*10+r;
}
cout<<"Reverse of number "<<n<<" is "<<rev; return 0;
}
This Should Reverse it.
+ 5
I am just a beginner in c++. @Akash_pal helped me to solve this problem a time ago.
+ 3
Wait a second, how does your code even work? Shouldn't there be an error because you're accessing outside array's bounds?
Upliking for visibility, someone explain this voodoo.
Also, it's better to put your code in playground and insert a link in your post. It's easier to read.
+ 3
declare int x[i] not correct. use for exmpl int x[10]
+ 1
@vishal pal
Yup more professional than mine xD
Thanks !
+ 1
Ok, I've looked into it. It's a fun thing called undefined behaviour. Basically, c++ doesn't mind you going outside of array bounds but your program will work only maybe probably sometimes.
If you don't mind waiting until tomorrow (because it's 2 am), I'll fix that code with minimal touches.
0
@BlazingMagpie
Well it woks perfectly untill you enter more than 6 numbers , it only sees the first 6 and reverse them.
Yet it works
Next time I will insert a link thanks for the tip
0
@BlazingMagpie
Ok, I’m waiting
0
https://code.sololearn.com/c7KJ1UmVF534/?ref=app
I know you all have already discussed but this is my code. Which I posted almost a month ago for sololearn Q&A section only.