C – Reverse a Number
To reverse a given integer in C programming, pop the last digit of the given number in a loop, and append it to a new number. At the end of iteration, we end up with the reversed number in the result.
C Program
In the following program, we read a number to n from user via console input, and reverse this number.
main.c
</>
Copy
#include <stdio.h>
int main() {
int n;
printf("Enter a number : ");
scanf("%d", &n);
int reversed = 0;
int temp = n;
while (temp > 0) {
reversed = (reversed * 10) + (temp % 10);
temp = temp / 10;
}
printf("Reversed Number : %d\n", reversed);
}
Output
Enter a number : 1234
Reversed Number : 4321
Program ended with exit code: 0
Output
Enter a number : 4466
Reversed Number : 6644
Program ended with exit code: 0
We have used C While Loop to iterate over the digits of the given number.
Conclusion
In this C Tutorial, we learned how to reverse a number in C programming, with example programs.