Here is a C program to reverse the digits of a number. This program first take an integer as input form user, then reverse it's digits using modulus(%), division(/) and multiplication(*) operator inside loop. After reversing it prints the reversed number.
Inside loop, we first get the least significant digit(right most digit) of number using (number % 10) then append it at the end of reverse number. Finally we remove right most digits from number in number = number/10 statement.
C program to reverse digit of a number using loop
- Get the least significant digit(right most digit) of the number.
rightDigit = number%10; - Append it at the end of reverse number.
reverse = (reverse * 10) + rightDigit; - Remove right most digit from number.
number = number/10; - Repeat this process till number is greater than zero.
#include <stdio.h> int main(){ int number, reverse = 0, rightDigit; printf("Enter a number \n"); scanf("%d", &number); while(number != 0){ rightDigit = number % 10; reverse = (reverse * 10) + rightDigit; number = number/10; } printf("Reversed number : %d\n", reverse); return 0; }Output
Enter a number : 12345 Reversed number : 543211
C program to reverse digits of a number using recursion
We can use recursion to reverse the digits if a number because it follows recursive sub-problem property.
getReversedNumber(1234) = (4*1000) + getReversedNumber(123)
This program uses a function getReversedNumber which takes a number as input and returns reversed number.
- N%10 returns the least significant digit of N(354%10 = 4).
- N/10 return the number after removing least significant digit of N(2345/10 = 234).
- log10(N) + 1 returns the number of digits in N. log10(N) is logarithm of N with base 10(log10(2311) + = 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)
#include <stdio.h> #include <math.h> int getReversedNumber(int number); int main(){ int number, reverse = 0; printf("Enter a number :"); scanf("%d", &number); reverse = getReversedNumber(number); printf("Reversed number : %d\n", reverse); getch(); 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 : 23148 Reversed number : 84132
Related Topics