Here is a C program to reverse digits of 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 : 25346After reverse : 64352
- 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
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.
#include <stdio.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); return 0; } 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; numberOfDigits = log10(number) + 1; return (lastDigit*pow(10,numberOfDigits) + getReversedNumber(number))*sign; }Output
Enter a number 6542 Reversed number : 2456
Related Topics