Write a C program to reverse a number
Description: Take a number as input and print it in reverse order, like 1234 as 4321.
Hint:
- Take the last digit with
% 10, add it to the reversed number, and remove it with/ 10.
C program to reverse a number
#include <stdio.h>
int main(void) {
int n, reversed = 0;
printf("Enter a number: ");
scanf("%d", &n);
while (n != 0) {
int digit = n % 10;
reversed = reversed * 10 + digit;
n /= 10;
}
printf("Reversed number = %d\n", reversed);
return 0;
}
Output:
Output of the above program is
Enter a number: 1234
Reversed number = 4321
How it works
- Round 1: digit 4, reversed = 4, n = 123.
- Round 2: digit 3, reversed = 43, n = 12.
- It continues until n is 0, and the answer is 4321.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |