In this tutorial, you will learn how to reverse a number using c programming.
C Program to Reverse a Integer
#include <stdio.h>
int main() {
int num, rev = 0;
// Read the number from the user
printf("Enter a number: ");
scanf("%d", &num);
// Reverse the number
while (num > 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
// Print the reversed number
printf("Reversed number: %d\n", rev);
return 0;
}
Output
Enter a number: 1234
Reversed number: 4321
Explanation
- The program first reads the number from the user using
scanf(). - It then initializes a variable
revto0and enters a loop. The loop continues as long asnumis greater than0. - Inside the loop,
revis updated torev * 10 + num % 10. This effectively appends the last digit ofnumtorev. For example, ifnumis123andrevis0, then after the first iteration,revwill be3, after the second iteration it will be30, and after the third iteration it will be300. numis then updated tonum / 10, which removes the last digit. For example, ifnumis123, it will become12after the first iteration,1after the second iteration, and0after the third iteration, at which point the loop will terminate.- Finally, the reversed number is printed using
printf().
You can find more C Programming Examples here.
Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.
