C Program To Reverse A Number
C PROGRAM TO REVERSE A NUMBER
#include <stdio.h>
int main() {
int n, rev = 0, remainder;
printf("Enter an integer: ");
while( n != 0) {
remainder = n % 10;
rev = rev * 10 + remainder;
n /= 10;
}
printf("Reversed number is: %d", rev);
return 0;
}
Output
Enter an integer: 9929
Reversed number is: 9299
______________________________________________
How the program works?
- The program takes input from the scanf() function.
- Then while() loop is used until n != 0 becomes false.
- In each iteration of the while loop, the remainder when n is divided by 10 is calculated and the value of n is reduced by 10 times.
- In the loop, the integer is reversed using-
rev = rev * 10 + remainder;
- Then printf() function, at last, returns the reversed integer.
Comments
Post a Comment