For working professionals
For fresh graduates
More
Explore C Tutorials: From Begi…
1. Introduction to C Tutorial
2. Addition of Two Numbers in C
3. Anagram Program in C
4. Armstrong Number in C
5. Array in C
6. Array of Pointers in C
7. Array of Structure in C
8. C Program to Find ASCII Value of a Character
9. Assignment Operator in C
10. Binary Search in C
11. Binary to Decimal in C
12. Bitwise Operators in C
13. Boolean in C
14. C Compiler for Mac
15. C Compiler for Windows
16. C Function Call Stack
17. C Language Download
18. Operators in C
19. C/C++ Preprocessors
20. C Program for Bubble Sort
21. C Program for Factorial
22. C Program for Prime Numbers
23. C Program for String Palindrome
24. C Program to Reverse a Number
Now Reading
25. Reverse a String in C
26. C string declaration
27. String Input Output Functions in C
28. Calculator Program in C
29. Call by Value and Call by Reference in C
30. Ceil Function in C
31. Coding Vs. Programming
32. Command Line Arguments in C/C++
33. Comments in C
34. Compilation process in C
35. Conditional Statements in C
36. Conditional operator in the C
37. Constant Pointer in C
38. Constants in C
39. Dangling Pointer in C
40. Data Structures in C
41. Data Types in C
42. Debugging C Program
43. Convert Decimal to Binary in C
44. Define And include in C
45. Difference Between Arguments And Parameters
46. Difference Between Compiler and Interpreter
47. Difference Between If Else and Switch
48. Do While Loop In C
49. Double In C
50. Dynamic Array in C
51. Dynamic Memory Allocation in C
52. Enumeration (or enum) in C
53. Evaluation of Arithmetic Expression
54. Factorial of A Number in C
55. Features of C Language
56. Fibonacci Series Program in C Using Recursion
57. File Handling in C
58. For Loop in C
59. Format Specifiers in C
60. Functions in C
61. Function Pointer in C
62. goto statement in C
63. C Hello World Program
64. Header Files in C
65. Heap Sort in C Program
66. Hello World Program in C
67. History of C Language
68. How to compile a C program in Linux
69. How to Find a Leap Year Using C Programming
70. Identifiers in C
71. If Else Statement in C
72. If Statement in C
73. Implementation of Queue Using Linked List
74. Increment and decrement operators in c
75. Input and Output Functions in C
76. How To Install C Language In Mac
77. Jump Statements in C
78. Lcm of Two Numbers in C
79. Length of an Array in C
80. Library Function in C
81. Linked list in C
82. Logical Operators in C
83. Macros in C
84. Matrix multiplication in C
85. Nested if else statement in C
86. Nested Loop in C
87. One Dimensional Array in C
88. Operator Precedence and Associativity in C
89. Overflow And Underflow in C
90. Palindrome Program in C
91. Pattern Programs in C
92. Pointer to Pointer in C
93. Pointers in C: A Comprehensive Tutorial
94. Pre-increment And Post-increment
95. Prime Number Program in C
96. Program for Linear Search in C
97. Pseudo-Code In C
98. Random Access Files in C
99. Random Number Generator in C
100. Recursion in C
101. Relational Operators in C
102. Simple interest program in C
103. Square Root in C
104. Stack in C
105. Stack Using Linked List in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
112. String Comparison in C
113. String Functions in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
118. Structure of C Program
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
122. Toupper Function in C
123. Transpose of a Matrix in C
124. Two Dimensional Array in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
129. User Defined Functions in C
130. What is Variables in C
131. Is C language case sensitive
132. Fibonacci Series in C
Reversing a number is a fundamental programming problem that many programmers encounter in their journey. It's a simple concept but can help understand core programming principles like loops, conditional statements, and mathematical operations.
In this tutorial, you will explore how to reverse a number using the C programming language, starting from a fundamental approach and moving on to more complex implementations.
Let’s dive into the first step: reversing a number in C using an iterative approach.
Reversing a number in C might seem simple at first, but it requires a solid understanding of how loops, mathematical operations, and data manipulation work together. Let’s break this down carefully.
When we reverse a number, we need to:
Let's go through the approach step by step:
Now, here’s the code implementation for it:
#include <stdio.h>
int main() {
int num, reversed = 0, remainder;
// Asking the user to input a number
printf("Enter an integer: ");
scanf("%d", &num); // Input number from the user
// Reversing the number using a while loop
while (num != 0) {
remainder = num % 10; // Extract the last digit
reversed = reversed * 10 + remainder; // Append the last digit to the reversed number
num /= 10; // Remove the last digit from the original number
}
// Output the reversed number
printf("Reversed Number: %d\n", reversed);
return 0;
}
Output Example:
Let’s walk through an example to see what happens when you enter 12345 as input:
Enter an integer: 12345
Reversed Number: 54321
Code Explanation:
By repeating this process in the while loop, we continue extracting the last digit of the number, building up the reversed number until the original number is reduced to 0.
Improve your C programming skills with our software development courses — take the next step in your learning journey!
A flowchart is a great way to visualize the sequence of steps your program follows. Let’s break down the steps in a simple flowchart:
Here’s a simple flowchart that summarizes the process:
+------------------------+
| Start Program |
+------------------------+
|
v
+------------------------+
| Input the number |
+------------------------+
|
v
+------------------------+
| Initialize reversed = 0|
+------------------------+
|
v
+------------------------+
| While num != 0 |
+------------------------+
|
v
+------------------------+
| Extract last digit |
| Update reversed number |
+------------------------+
|
v
+------------------------+
| Remove last digit from |
| original number |
+------------------------+
|
v
+------------------------+
| Output the reversed |
| number |
+------------------------+
|
v
+------------------------+
| End Program |
+------------------------+
Also Read: Types of Operators in C: Roles, Usage & Best Practices 2025
An algorithm is a series of steps you can follow to solve a particular problem; in this case, the problem reverses a number. By following a well-defined algorithm, you ensure your solution works in a systematic and reliable way.
So let’s look at the steps of the algorithm to reverse a number.
Algorithm:
Pseudocode:
Here’s a high-level pseudocode for the algorithm:
START
INPUT num
SET reversed = 0
WHILE num != 0 DO
remainder = num % 10
reversed = reversed * 10 + remainder
num = num / 10
END WHILE
PRINT reversed
END
This pseudocode simplifies the process into basic operations: extracting digits, updating the reversed number, and removing digits from the original number.
Now that you understand the algorithm, let’s go ahead and implement it in C.
Here. you will break down the steps required to implement the algorithm and explain how each part of the program works. The goal is to provide a detailed understanding of how the logic is translated into C code.
Key Steps for Implementation:
Here’s the complete code implementation of it in C:
#include <stdio.h>
int main() {
int num, reversed = 0, remainder;
// Step 1: Asking the user to input a number
printf("Enter an integer: ");
scanf("%d", &num); // Taking input from the user
// Step 2: Reversing the number using a while loop
while (num != 0) {
remainder = num % 10; // Extract the last digit
reversed = reversed * 10 + remainder; // Build the reversed number
num /= 10; // Remove the last digit from num
}
// Step 3: Output the reversed number
printf("Reversed Number: %d\n", reversed);
return 0;
}
Output Example:
Let's go through an example to understand the output better.
Enter an integer: 12345
Reversed Number: 54321
Enter an integer: 987
Reversed Number: 789
Here’s the detailed code explanation:
1. Input Section:
2. Reversal Logic (While Loop):
First Iteration:
Second Iteration:
Third Iteration:
Fourth Iteration:
Fifth Iteration:
Now, since num is 0, the while loop exits, and the program prints the final reversed number, which is 54321.
3. Output:
There you go! Once the while loop ends, the program outputs the reversed number using printf(). For our example input 12345, the output will be 54321.
As you have used an iterative approach to reverse a number, you can also achieve this using recursion. Let’s see ahead!
Recursion is when a function calls itself in order to break down a problem into smaller, simpler subproblems. The recursive approach for reversing a number works by breaking the problem into two parts: reversing the number without the last digit and adding the last digit at the appropriate place.
#include <stdio.h>
int reverse(int num, int reversed) {
if (num == 0) {
return reversed; // Base case: when num is 0, return the reversed number
} else {
// Recursive case: extract the last digit and call reverse function again
return reverse(num / 10, reversed * 10 + num % 10);
}
}
int main() {
int num;
// Step 1: Asking the user to input a number
printf("Enter an integer: ");
scanf("%d", &num); // Input the number from the user
// Step 2: Call reverse function to reverse the number
int reversed = reverse(num, 0);
// Step 3: Output the reversed number
printf("Reversed Number: %d\n", reversed);
return 0;
}
Output Example:
#Example 1
Enter an integer: 12345
Reversed Number: 54321
#Example 2
Enter an integer: 987
Reversed Number: 789
Code Explanation:
1. Recursive Function (reverse):
The function reverse() takes two arguments: the current number (num) and the reversed number so far (reversed).
2. Main Function:
The main() function takes input from the user and calls the reverse() function, passing the input number and an initial reversed value of 0. The result is stored in the reversed variable, which is then printed.
Recursion can be elegant and concise, but it’s important to ensure that the base case is properly defined to prevent infinite recursion.
While reversing a number works well for positive integers, negative numbers require special handling due to the negative sign. If you don’t account for the negative sign, the program might return an incorrect result or behave unexpectedly.
When reversing a negative number, you don’t want the negative sign to be reversed. Instead, the negative sign should remain in place at the front of the reversed number.
To handle negative numbers correctly:
#include <stdio.h>
#include <stdlib.h> // For abs() function
int reverse(int num, int reversed) {
if (num == 0) {
return reversed;
} else {
return reverse(num / 10, reversed * 10 + num % 10);
}
}
int main() {
int num;
// Step 1: Asking the user to input a number
printf("Enter an integer: ");
scanf("%d", &num);
// Step 2: Check if the number is negative
int isNegative = (num < 0); // 1 if negative, 0 if positive
if (isNegative) {
num = -num; // Make the number positive for reversal
}
// Step 3: Reverse the number
int reversed = reverse(num, 0);
// Step 4: If the number was negative, add the negative sign to the result
if (isNegative) {
reversed = -reversed;
}
// Step 5: Output the reversed number
printf("Reversed Number: %d\n", reversed);
return 0;
}
Output Example:
#Example 1
Enter an integer: -12345
Reversed Number: -54321
#Example 2
Enter an integer: 987
Reversed Number: 789
Code Explanation:
If the number is negative, we set isNegative to 1 and make num positive by using num = –num.
Handling such edge cases ensures that your number reversal function is robust and can work in a variety of real-world scenarios.
Reversing numbers might seem like a simple problem at first, but it actually plays a critical role in a variety of real-world applications across different fields of software engineering.
Let’s take a closer look at some use cases where number reversal can be applied:
1. Palindrome Checking:
One of the most common use cases of number reversal is in checking whether a number is a palindrome. A palindrome is a number that reads the same forwards and backwards (e.g., 121 or 12321).
To check if a number is a palindrome, we reverse the number and compare it with the original one. If both are the same, the number is a palindrome.
Example: Check if 121 is a palindrome:
2. Checksum Algorithms:
In data integrity and transmission, checksums are used to detect errors. Reversing a number can be part of an algorithm that calculates the checksum.
By reversing and performing arithmetic operations on a number, you can create a unique checksum value that helps verify the correctness of data transmission.
3. Cryptography and Data Security:
Certain cryptographic algorithms, especially those dealing with number manipulation and key generation, use number reversal techniques. Reversing numbers can be used as part of encryption/decryption processes, where reversing or altering digits is one step in generating a secure key or decoding information.
4. Mathematical Operations and Algorithms:
In number theory and algorithm design, reversing numbers is often part of a larger problem. For example, reversing numbers is sometimes used in algorithms that generate patterns or solve specific types of puzzles.
In some sorting and searching algorithms, reversing the digits of numbers might be necessary as part of the problem-solving process.
5. Data Validation and Error Detection:
Reversing numbers can also be a part of data validation. For example, in some systems, phone numbers, account numbers, or serial numbers might be validated by reversing them and checking for consistency or patterns.
This is a method used to ensure that the data provided is valid and conforms to the expected format.
Understanding how and why to reverse a number gives you a deeper insight into how numbers are manipulated in computer science.
While the process of reversing a number might seem straightforward, there are several common pitfalls and errors that beginners often encounter.
Let’s go through some of these errors and see how to avoid them.
1. Not Handling Negative Numbers Properly:
One of the most common errors is not handling negative numbers correctly. The output will be incorrect if the negative sign is included in the reversal process. Always ensure that the negative sign is handled separately from the digits.
Solution: Convert the number to positive before reversing and then restore the sign at the end if the number is negative.
2. Integer Overflow:
Another issue that may arise when reversing numbers is an integer overflow. In C, the size of an int is limited (typically 32 bits), so if the reversed number exceeds this limit, it can cause overflow and produce incorrect results.
Suppose the input number is 999999999. When reversed, it becomes 999999999, which exceeds the limit for a 32-bit integer and causes overflow.
Solution: Check for overflow by verifying whether the reversed number exceeds the limits of the data type (e.g., INT_MAX or INT_MIN in C). Alternatively, use a larger data type such as long long int for very large numbers.
3. Handling Leading Zeros:
When reversing a number, you might encounter situations where the reversed number contains leading zeros. For example, reversing 100 would result in 001, which is just 1. These leading zeros should be discarded.
Solution: Since numbers do not have leading zeros in their decimal representation, there is no need to worry about removing them. The process of reversing will naturally discard the zeros, as they will not be added to the reversed number.
4. Off-by-One Errors:
Sometimes, beginners might face off-by-one errors when implementing the reversal algorithm. This happens when the loop conditions or how digits are extracted are slightly off, leading to incorrect results.
Solution: Carefully check the logic in the loop, ensuring the number is correctly processed (i.e., the digits are extracted and added in the correct order).
5. Incorrect Handling of Single-Digit Numbers:
Single-digit numbers, such as 5 or 9, might confuse beginners. When reversed, these numbers should remain unchanged.
Solution: Ensure the reversal logic works for all numbers, even single-digit numbers. The reversal of a single-digit number will just return the number itself, which is a valid case.
6. Edge Cases with Zero:
Another common pitfall is when the number is zero. Reversing 0 should result in 0, but some beginners might mistakenly produce an error or an unexpected output.
Solution: Handle the special case where the input number is 0 before the reversal logic begins.
By following the techniques and examples you now have a strong foundation for reversing numbers in C, and you are ready to apply these skills to more advanced problems.
Also Read: Top 25+ C Programming Projects for Beginners and Professionals
Test your understanding of the topic with the following multiple-choice questions. These questions focus on concepts related to reversing numbers in C, and two of them include code output questions.
#include <stdio.h>
int main() {
int num = 1234;
int reversed = 0, remainder;
while (num != 0) {
remainder = num % 10;
reversed = reversed * 10 + remainder;
num /= 10;
}
printf("%d", reversed);
return 0;
}
A) 4321
B) 1234
C) 1045
D) Error
#include <stdio.h>
int reverse(int num, int reversed) {
if (num == 0)
return reversed;
return reverse(num / 10, reversed * 10 + num % 10);
}
int main() {
int num = 500;
printf("%d", reverse(num, 0));
return 0;
}
A) 5
B) 500
C) 0
D) Error
3. Which of the following is the correct way to handle a negative number in a number reversal program?
A) Reverse the number and then negate the reversed result.
B) Reverse the absolute value of the number and then negate the result.
C) Reverse the number without worrying about the sign.
D) None of the above.
4. What type of error is most likely to occur when reversing a very large number in C?
A) Syntax error
B) Logic error
C) Integer overflow
D) Runtime error
5. What is the correct way to check if a number is a palindrome using a number reversal technique?
A) Reverse the number and compare it to the original number.
B) Reverse the number and check if it is divisible by 2.
C) Reverse the number and check if the sum of digits is the same as the reversed number.
D) Reverse the number and compare the sum of digits to the original number.
6. What will be the output if the user inputs 0 in the number reversal program?
A) 0
B) 1
C) Error
D) Undefined behavior
7. Which of the following algorithms uses the concept of reversing a number as part of its process?
A) Bubble sort
B) Binary search
C) Checksum algorithm
D) Merge sort
8. What happens if you don’t handle the negative sign properly when reversing a negative number?
A) The program will return an incorrect value, including the negative sign in the wrong position.
B) The program will crash.
C) The program will return the original number.
D) The program will reverse the number as intended.
9. What is the maximum size of a number that can be safely reversed using a 32-bit integer in C?
A) 999999999
B) 2147483647
C) 1000000000
D) 4294967296
10. Which of the following is true about recursion in reversing a number?
A) Recursion requires more memory and can lead to stack overflow for large numbers.
B) Recursion is always more efficient than the iterative approach.
C) Recursion does not require a base case.
D) Recursion does not need to call itself for number reversal.
Mastering the concept of reversing a number in C not only enhances your basics but also equips you with the skills to tackle a wide range of real-world problems. Keep practicing, and these concepts will become second nature in your coding journey!
Also Read: 25 Most Common C Interview Questions & Answers [For Freshers]
upGrad’s courses provide in-depth training in C programming, covering fundamental concepts like loops, recursion, functions, and pointers. You’ll gain hands-on experience writing efficient C programs, including factorial calculations, data structures, and algorithm optimization.
By learning C programming, you’ll build a strong foundation for software development, competitive programming, and system-level programming.
Check out some of these upGrad courses to take your programming skills to the next level!
You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!
Similar Reads:
Explore C Tutorials: From Beginner Concepts to Advanced Techniques
Addition of Two Numbers in C: A Comprehensive Guide to C Programming
String Anagram Program in C
C Program to check Armstrong Number
Array in C: Introduction, Declaration, Initialisation and More
Exploring Array of Pointers in C: A Beginner's Guide
What is C Function Call Stack: A Complete Tutorial
Discovering C Operators: An Overview with Types and Examples!
Binary Search in C
Conditional Operator in C
Constant Pointer in C: The Fundamentals and Best Practices
Constants in C Explained
Dangling Pointer in C: Causes, Risks, and Prevention Techniques
Find Out About Data Structures in C and How to Use Them?
C Program to Convert Decimal to Binary
Q. What is the primary purpose of reversing a number in C?
A. Reversing a number is often used in algorithms, data validation, and error detection and is a fundamental exercise to understand number manipulation and control structures in programming.
Q. How can I reverse a number in C without a loop?
A. You can reverse a number using recursion, where the function calls itself to reduce the problem size and rebuild the reversed number.
Q. Can I reverse a negative number in C?
A. To reverse a negative number, you should first reverse the absolute value and then reapply the negative sign at the end.
Q. What happens if the reversed number exceeds the limit of a 32-bit integer?
A. If the reversed number exceeds the maximum value of an integer, it will result in integer overflow, which leads to incorrect results.
Q. How do I check if a number is a palindrome in C?
A. You can reverse the number and compare it to the original number. If both are the same, the number is a palindrome.
Q. Is there a built-in function in C to reverse a number?
A. No, C has no built-in function for reversing a number. It must be implemented manually using loops or recursion.
Q. How can I handle leading zeros when reversing a number?
A. Leading zeros are automatically discarded in the reversed number, as numbers don't store leading zeros in their decimals.
Q. What is the algorithm's time complexity to reverse a number in C?
A. The time complexity is O(n), where n is the number of digits in the number. Each digit is processed once.
Q. Can I reverse a decimal or floating-point number in C?
A. The reversal algorithm works for integers. The digits after the decimal point would require separate handling for floating-point numbers, as the algorithm is designed for whole numbers.
Q. Why should I avoid using recursion for large numbers?
A. Recursion uses the system's stack to store intermediate function calls, and for large numbers, this can lead to a stack overflow error.
Q. What is the best approach for reversing a number in C?
A. The iterative approach is often the most efficient, especially for large numbers, as it avoids the overhead associated with recursion.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.