Reversing a number is a classic problem in programming that tests your logical thinking and understanding of loops. Whether you’re a fresher or a new learner diving into C programming, this is a great way to enhance your skills in handling loops like while, do-while, and for.
In this post, we’ll provide practice questions to reverse a number using all three types of loops in C. These exercises will solidify your understanding of iteration and logic, helping you ace interviews and coding challenges.
Understanding the Problem
Reversing a number means rearranging its digits in reverse order. For example:
- Input:
1234 - Output:
4321
To achieve this, we can:
- Extract the last digit using the modulus operator (
%). - Append it to the reversed number.
- Remove the last digit using integer division (
/).
Reversing a Number Using While Loop
Code Example 1: Reverse a Number Using While Loop
#include <stdio.h>
int main() {
int num, reverse = 0, remainder;
printf("Enter a number: ");
scanf("%d", &num);
while (num != 0) {
remainder = num % 10;
reverse = reverse * 10 + remainder;
num /= 10;
}
printf("Reversed Number: %d\n", reverse);
return 0;
}
Reversing a Number Using Do-While Loop
Code Example 2: Reverse a Number Using Do-While Loop
#include <stdio.h>
int main() {
int num, reverse = 0, remainder;
printf("Enter a number: ");
scanf("%d", &num);
do {
remainder = num % 10;
reverse = reverse * 10 + remainder;
num /= 10;
} while (num != 0);
printf("Reversed Number: %d\n", reverse);
return 0;
}
Reversing a Number Using For Loop
Code Example 3: Reverse a Number Using For Loop
#include <stdio.h>
int main() {
int num, reverse = 0, remainder;
printf("Enter a number: ");
scanf("%d", &num);
for (; num != 0; num /= 10) {
remainder = num % 10;
reverse = reverse * 10 + remainder;
}
printf("Reversed Number: %d\n", reverse);
return 0;
}
Practice Questions
- Modify the code to handle negative numbers.
- Write a program to reverse multiple numbers entered by the user.
- Create a function to reverse a number and call it from the
mainfunction. - Implement the reversal logic for floating-point numbers.
- Write a program to check if a number is a palindrome (same forward and backward).
Pro Tips for Beginners
- Understand the logic: Focus on extracting digits and forming the reversed number.
- Practice all loop types: Each loop has its use case, so try implementing the logic with different loops.
- Debug with print statements: Use
printfto print intermediate results and understand the flow. - Think of edge cases: Test your program with inputs like
0,1000, and negative numbers.
Conclusion
Mastering loops and basic logic like reversing a number is crucial for any beginner in C programming. These examples and practice questions will help you build confidence and improve your coding skills. Keep experimenting, and don’t hesitate to apply similar logic to other problems!

