Reversing Numbers | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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; }

14th Jan 2018, 12:20 AM
Eslam Khaled
Eslam Khaled - avatar
10 Answers
+ 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.
14th Jan 2018, 12:24 AM
Vishal Pal❄️⚛️
Vishal Pal❄️⚛️ - avatar
+ 5
I am just a beginner in c++. @Akash_pal helped me to solve this problem a time ago.
14th Jan 2018, 12:37 AM
Vishal Pal❄️⚛️
Vishal Pal❄️⚛️ - avatar
+ 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.
14th Jan 2018, 12:29 AM
BlazingMagpie
BlazingMagpie - avatar
+ 3
declare int x[i] not correct. use for exmpl int x[10]
14th Jan 2018, 1:19 AM
UraL
+ 1
@vishal pal Yup more professional than mine xD Thanks !
14th Jan 2018, 12:35 AM
Eslam Khaled
Eslam Khaled - avatar
+ 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.
14th Jan 2018, 12:40 AM
BlazingMagpie
BlazingMagpie - avatar
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
14th Jan 2018, 12:37 AM
Eslam Khaled
Eslam Khaled - avatar
0
@BlazingMagpie Ok, I’m waiting
14th Jan 2018, 12:48 AM
Eslam Khaled
Eslam Khaled - avatar
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.
14th Jan 2018, 2:39 AM
Hrishikesh Kulkarni
Hrishikesh Kulkarni - avatar
14th Jan 2018, 8:15 AM
BlazingMagpie
BlazingMagpie - avatar