-2

I have a small simple school project for c programming. I am supposed to write a number and get the reverse of it and I couldn't understand how this code works. So, I need someone to explain to me what happens in the while loop, and why we use these operations, and whats %10?

Thanks!

/* Reverse number using while loop */

#include<stdio.h>
int main()
{
    int num, reverse=0;
    scanf("%d",&num);
    while(num > 0)
    {
        reverse= reverse*10;
        reverse = reverse + (num%10);
        num = num/10;
    }
    printf("%d",reverse);
    return 0;
}
hobaa
  • 71
  • 6

2 Answers2

0

'While loop' repeats the number of entered numbers.

'num%10' means the remainder of num divided by 10. This is the process to know the numbers at the end.

For example, if you enter '123' then while loop will repeat 3 times.

The first step, reverse -> 3, num -> 12

Second, reverse -> 30 -> 32, num -> 1

Third, reverse -> 320 -> 321, num -> 0

Therefore you can get the reverse number!

0

In your code while loop is the place where the digits of the entered number get reversed and stored as another number - reverse. In order to do that the last digits of the original number need to be accessed first. The % modulo operator returns the remainder of the division. Since you are dividing the original number by 10 you get the last digit of it, which is the remainder. We need to store that digit as the first of the reversed number and albo somehow get to the next digits of the original number. To store consequtive digits you multiply currently existing reversed number by 10 and add the next digit. That way you add next digit to the right of reverse, eventually, after adding all digits, getting the complete reversed number. Getting to the next digits of the original number uses the property of the division / operator which leaves the quotient of the division. When dividing by 10 it "cuts off" the last digit of the given number. That also explains the condition in the while loop: when your number becomes 0 it means you have gone through all of its digits.