In this article, we will learn how to write a C program to reverse a number. For example, if the given number is 1234 then program should return number 4321 as output. We will see two different ways to accomplish this.
Example 1: C Program to reverse a given number using Recursion
In this program, we are using a recursive function reverse_function
to reverse a user entered number. The explanation of the program is at the end of the following code.
#include <stdio.h>
int revNum=0, rem;
int reverse_function(int num){
if(num){
rem=num%10;
revNum=revNum*10+rem;
reverse_function(num/10);
}
else
return revNum;
return revNum;
}
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:
reverse_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 revNum
(because of this logic revNum=revNum*10+rem
). This process keeps going on until all digits are removed from original number in reverse order and appended to the variable revNum
. At the end of the recursion, this revNum
variable contains the reverse of the original number.
Example 2: C Program to reverse a number using While loop
In this program, we are reversing the input number using while loop. The explanation of the while loop is available at the end of the program.
#include <stdio.h> int main() { int num, revNum = 0, remainder; // Prompt user to enter an integer number printf("Enter an integer: "); // store the input number in variable num scanf("%d", &num); // loop to reverse the entered number while (num != 0) { // Get the last digit remainder = num % 10; // Append it to the revNum revNum = revNum * 10 + remainder; // Remove the last digit from the original number num /= 10; } // print the revNum as output printf("Reversed Number: %d\n", revNum); return 0; }
Output:
Enter an integer: 1234
Reversed Number: 4321
How the loop works:
- The
num % 10
operation fetches the last digit ofnum
. - The revNum =
revNum * 10 + remainder
operation appends the last digit to the reversed number. - The
num /= 10
operation removes the last digit fromnum
. - The loop continues until
num
becomes 0.
Leave a Reply