C Program to Reverse a Number
In programming, we can display the reversed number by printing all its digits from the rightmost digit to the left-most integer. But, to retain it as a number, we apply some math to store the value at each iteration.
Algorithm to Reverse a Number in C
- Initialize rev_num to 0 // variable to hold the reverse of a number in c
- While num > 0 // Loop until there are no more digits in num a. Extract the last digit of num: digit = num % 10 b. Append digit to rev_num: rev_num = rev_num * 10 + digit c. Remove the last digit from num: num = num / 10
- Return rev_num // rev_num now contains the reversed number
C Program to Reverse a Number in C
Using While Loop
Code:
Output:
Explanation: Let's break down the operation of the while loop for the given reverse number program in c, input number n is 12345.
n | n!=0 | remainder | reversed_number (new) |
---|---|---|---|
12345 | true | 5 | 0 * 10 + 5 = 5 |
1234 | true | 4 | 5 * 10 + 4 = 54 |
123 | true | 3 | 54 * 10 + 3 = 543 |
12 | true | 2 | 543 * 10 + 2 = 5432 |
1 | true | 1 | 5432 * 10 + 1 = 54321 |
0 | false | - | Loop terminates |
Finally, reversed_number, now holding the reversed sequence of digits, is displayed as output.
Complexity Analysis
Time complexity: Space complexity:
Using Recursion
Code:
Output:
Explanation: The function reverse_number explains how to reverse a number in c using recursive calls, shrinking number by a factor of 10 each time, and accumulates the reversed number using the remainder.
Complexity Analysis
Time complexity:
Space complexity: ,due to recursive call stack
Using For Loop
Code:
Output:
Explanation: The code uses a for loop to iterate through digits of number, extracting and appending each digit to reversed_number until i becomes 0.
Complexity Analysis
Time complexity:
Space complexity:
Using Function
Code:
Output:
Explanation: In this approach, the reverse_number function reverses the input number by repeatedly extracting its last digit and building the reversed_number in a while loop.
Complexity Analysis
Time complexity:
Space complexity:
Note: When reversing a negative number in C, first convert it to positive by multiplying by -1, reverse it, then convert back to negative by multiplying by -1 again, to ensure accurate results.
Flow of the Program to Reverse a Number in C
Conclusion
Representing Number as Array:
- Each digit is set to store in the array. Read the number directly into an array of characters or use a loop to store each digit from the number.
- Reverse the array using strrev() in the string.h header file.
- Inputs having trailing zeroes should be discarded as they are no longer worth.