Reverse a Number in C
In this program, You will get and learn the program code of Reverse a Number in C programming. This program is briefly explain with algorithm, DFD (Data Flow Diagram), and program code.
Here you will know to create Reverse a Number program by using 3 different kinds of methods.
How to Reverse a Number
The reverse number is a mathematical operation where the digits of a number are reversed from the backyard. For example, if the number is 12345, the reverse number would be 54321.
Reverse Number Algorithm
Step 1. Input number from user.
Step 2. Get the remainder, quotient of number, by dividing 10.
Step 3. Multiply result variable by 10, then Add remainder in that.
Step 4. Replace number by quotient.
Step 5. Repeat Step 2,3,4 till then number is greater then 0.
Step 6. Print result variable value as reverse number.
Reverse a Number DFD(Data Flow Diagram)
Reverse a Number in C using 3 different ways
#1. Reverse Number in C using while loop
#2. Reverse Number in C using functions
#3. Reverse Number in C using recursion
Reverse a Number in C using while loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //Reverse a Number #include<stdio.h> int main() { int num, num1, remainder, result = 0; printf("Enter a number: "); scanf("%d", &num); num1 = num; while (num != 0) { remainder = num % 10; result =(result*10)+remainder ; num = num / 10; } printf("nReverse digit of %d is %d.",num1,result); return 0; } |
Output
Reverse a Number in C using Functions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | //Reverse Number in C using Functions #include <stdio.h> int reverseNum(int num) { int reverse = 0; while(num > 0) { int remainder = num % 10; reverse = reverse * 10 + remainder; num /= 10; } return reverse; } int main() { int num; printf("Enter a number:"); scanf("%d", &num); int reversed = reverseNum(num); printf("Reversed Number of %d is %d",num, reversed); return 0; } |
Output
Reverse a Number in C using Recursion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // Reverse a number in c using recursion #include <stdio.h> int reverse(int num) { if(num > 0) { printf("%d", num%10); reverse(num/10); } } int main() { int num = 0; // Input number from user printf("Enter a number: "); scanf("%d", &num); printf("Reverse number of %d is: ", num); reverse(num); return 0; } |
Output
Program Explanation
1. Take the input integer number and store it in integer num variable.
2. divide num by 10, and obtain quotient and remainder.
3. Multiply result variable by 10 and add remainder.
4. replace num variable value by quotient.
5. repeat process until num not got zero.
6. Print the value of variable result as reverse of number.
Check out our other C programming Examples