C Program to Reverse an Integer
C program to reverse an integer.
C program to reverse an integer.
Write a program to reverse an integer using loops.
Input:
Enter an integer: 987654321
Output:
The reversed number is 12345789.
Input:
Enter an integer: 0
Output:
The reversed number is 0.
Input:
Enter an integer: -5678
Output:
The reversed number is -8765.
You need to write the complete program using the following template as the starter:
#include <stdio.h>
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
// Write your code here.
return 0;
}
Copy and paste the above code in your favorite IDE and start writing your code after the comment “// Write your code here.”
Pro tip: First, try writing the code on your own. Try every possible thing you can to come up with the solution. If you still can’t figure it out, then check the solution and see what went wrong. This is how you learn. 🙂
Input | Output | |
---|---|---|
Test Case 1 | 123 | 321 |
Test Case 2 | 1001 | 1001 |
Test Case 3 | -98 | -89 |
Test Case 4 | 0 | 0 |
Don’t forget to try the code on your own before diving into the solution.
The solution to the given problem is as follows:
// Program to reverse an integer
#include <stdio.h>
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
// Write your code here
int reversed = 0, remainder;
while (n != 0) {
remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}
printf("The reversed number is %d.", reversed);
return 0;
}
Let’s take a simple example to understand the flow of execution of the above program:
Assume that the number entered by the user is 123. So, n = 123.
The reversed number is 321 and that’s what we want.
Leave a comment