Could some one please explain exactly what is happening in this line of code. I\
ID: 672220 • Letter: C
Question
Could some one please explain exactly what is happening in this line of code. I'm having one of those moments when your code compiles and works, but you have no idea why. I just want a deeper understanding of what I've done instead of accepting it and moving on.
i = users input. this is a program to revers a sting of numbers.
while(i > 0)
{
//Want to know why * 10 into the input and then removing it by dividing it out later reverses the input.
reverse = reverse*10 + i%10;
i = i/10;
}
Explanation / Answer
Look at the below example
#include <stdio.h>
int main()
{
int n, reverse=0, rem;
printf("Enter an integer: ");
scanf("%d", &n);
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
}
printf("Reversed Number = %d",reverse);
return 0;
}
OUTPUT
Enter an integer: 312
Reversed Number = 213
Program Execution done like this
n=4562
rem=4562%10=2
reverse=0*10+2=2
n=4562/10=456
n=456
rem=456%10=6
reverse=2*10+6=26
n=456/10=45
n=45
rem=45%10=5
reverse=26*10+5=265
n=45/10=4
n=4
rem=4%10=4
reverse=265*10+4=2654
n=4/10=0