- Write a C program to reverse digits of a number using recursion
- Write a C program to reverse a number using recursion
Reversing the digits of a number means reversing the sequence of digits in a number. After reversing, least significant digit will become most significant digit of number and most significant digit becomes least significant digit and so on.
Let the total number of digits in a number is N. So a digit at ith position from left will become ith digit from right or N-i+1th digit from left.
For Example
Befor reverse : 25346
After reverse : 64352
Algorithm to reverse a number using recursion
- N%10 returns the last digit(least significant) of N. For Example : 354%10 = 4.
- N/10 return the number after removing least significant digit of N(rightmost digit of N). For Example: 2345/10 = 234.
- log10(N) + 1 returns the number of digits in N. log10(N) is logarithm of N with base 10. For Example: log10(2311) + 1 = 4.
- Let getReversedNumber(N) is a function, which returns reverse of N. Then, we can use recursion to reverse the digits if a number using below mention recursive equation.
- getReversedNumber(N) = (N%10)X pow(10, (log10(N/10) + 1)) + getReversedNumber(N/10)
For Example
- getReversedNumber(8645) = lastDigitOf(8645) x power(10, numberOfDigits(864)) + getReversedNumber(864)
- getReversedNumber(8645) = lastDigitOf(8645) x 1000 + getReversedNumber(864)
- getReversedNumber(8645) = 5×1000 + getReversedNumber(864)
- getReversedNumber(8645) = 5×1000 + 468
- getReversedNumber(8645) = 5468
C program to reverse the digits of a number recursively
This program first take an integer as input form user, then reverse it’s digits using modulus(%), division(/), multiplication(*) and logarithmic function inside a recursive function. After reversing it prints the reversed number.
/* * C Program to reverse the digits of a number using recursion */ #include <stdio.h> #include <conio.h> #include <math.h> int getReversedNumber(int number); int main(){ int number, reverse = 0; printf("Enter a number\n"); scanf("%d", &number); reverse = getReversedNumber(number); printf("Reversed number : %d\n", reverse); getch(); return 0; } /* * Function to reverse the digits of a number */ int getReversedNumber(int number){ int lastDigit, numberOfDigits, sign = 1; if(number < 0){ number = number * -1; sign = -1; } if(number < 10) return number*sign; lastDigit = number % 10; number = number / 10; /* log10(number) + 1 gives number of digits in number */ numberOfDigits = log10(number) + 1; /* * for Example: getReversedNumber(1234) = * ((4*1000) + getReversedNumber(321))*1 */ return (lastDigit*pow(10,numberOfDigits) + getReversedNumber(number))*sign; }
Program Output
Enter a number 6542 Reversed number : 2456