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
rev
to0
and enters a loop. The loop continues as long asnum
is greater than0
. - Inside the loop,
rev
is updated torev * 10 + num % 10
. This effectively appends the last digit ofnum
torev
. For example, ifnum
is123
andrev
is0
, then after the first iteration,rev
will be3
, after the second iteration it will be30
, and after the third iteration it will be300
. num
is then updated tonum / 10
, which removes the last digit. For example, ifnum
is123
, it will become12
after the first iteration,1
after the second iteration, and0
after 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.