In this tutorial, you will learn how to write a C program to reverse a given number. We will see two ways to reverse a number:
1) Using Recursion
2) Using While loop
Example 1: Program to reverse a given number using Recursion
In this program, we have created a user defined function reverse_function
, this function takes a number as a parameter and returns the reverse of this number.
Logic of this function: In this function, we are dividing the input number by 10 and assigning the remainder in a variable sum, the remainder is the last digit of the number. This function then calls itself for the number/10, the number/10 ensures that the number without last digit is passed to the same function again.
In the next iteration the second last digit becomes the second digit of sum
(because of this logic sum=sum*10+rem
). This process keeps going on until all digits are removed from original number in reverse order and appended to the variable sum
. At the end of the recursion, this sum
variables contains the reverse of the original number.
#include <stdio.h>
int sum=0,rem;
int reverse_function(int num){
if(num){
rem=num%10;
sum=sum*10+rem;
reverse_function(num/10);
}
else
return sum;
return sum;
}
int main(){
int num,reverse_number;
//Take the number as an input from user
printf("Enter any number:");
scanf("%d",&num);
//Calling user defined function to perform reverse
reverse_number=reverse_function(num);
printf("The reverse of entered number is :%d",reverse_number);
return 0;
}
Output:
Example 2: Program to reverse a number using While loop
In this program, we are reversing the input number using while loop.
#include <stdio.h>
int main()
{
int num,rem,reverseNum=0;
//Input number
printf("Enter an integer number: ");
scanf("%d",&num);
while(num>0)
{
rem = num%10;
reverseNum = reverseNum*10 + rem;
num = num/10;
}
printf("Reverse of the entered number is: %d", reverseNum);
return 0;
}
Output:
Enter an integer number: 8904 Reverse of the entered number is: 4098
Leave a Reply