Reverse a Number in C

Exercise:

Write a C Program to reverse a number.

Click Here to View the Solution!
#include <stdio.h>
int main() {
    int num, rev = 0, remainder;
    printf("Enter an integer: ");
    scanf("%d", &num);
    while (num != 0) {
        remainder = num % 10;
        rev = rev * 10 + remainder;
        num /= 10;
    }
    printf("Reversed number = %d", rev);
    return 0;
}
Click Here to View the Output!
Enter an integer: 9876467
Reversed number = 7646789
Click Here to View the Explanation!
  • This program is used to calculate the reverse of a number.
  • In main(), the program requests the user to enter a number and stores it in a integer variable n using the scanf() function.
  • The integer variable rev is initialized as rev = 0.
  • A while loop is initialized which will continue until num != 0 is true.
  • The remainder of num is calculated by taking modulus of num with 10.
  • The reverse of num is calculated by using the formula rev * 10 + remainder.
  • In each iteration, the value of num is reduced 10 times by dividing num by 10 which will be the value used in the next iteration.
  • When num becomes equal to 0, the loop exits, and the reverse number is printed.
  • The return 0 statement is used to exit the program execution.
%d bloggers like this: