Write a C program to input a number from user and find reverse of the given number using for loop. How to find reverse of any number using loop in C program. Logic to find reverse of a number in C programming.
Example
Input
Input number: 12345
Output
Reverse of 12345 = 54321
Required knowledge
Basic C programming, While loop
Logic to find reverse of a number
Step by step descriptive logic to find reverse of a number.
- Input a number from user to find reverse. Store it in some variable say num.
- Declare and initialize another variable to store reverse of num, say reverse = 0.
- Extract last digit of the given number by performing modulo division. Store the last digit to some variable say
lastDigit = num % 10
. - Increase the place value of reverse by one. To increase place value multiply reverse variable by 10 i.e.
reverse = reverse * 10
. - Add lastDigit to reverse i.e.
reverse = reverse + lastDigit
. - Since last digit of num is processed hence, remove last digit of num. To remove last digit divide num by 10 i.e.
num = num / 10
. - Repeat step 3 to 6 till num is not equal to (or greater than) zero.
Let us implement the above logic in C program.
Program to find reverse of a number
/**
* C program to find reverse of a number
*/
#include <stdio.h>
int main()
{
int num, reverse = 0;
/* Input a number from user */
printf("Enter any number to find reverse: ");
scanf("%d", &num);
/* Repeat the till 'num' becomes 0 */
while(num != 0)
{
/*
* Increase place value of reverse and
* add last digit to reverse
*/
reverse = (reverse * 10) + (num % 10);
/* Remove last digit from 'num' */
num /= 10;
}
printf("Reverse = %d", reverse);
return 0;
}
Take a step forward and learn this program using recursive approach.
Learn more – Program to find reverse of any number using recursion.
Output
Enter any number to find reverse: 12345 Reverse = 54321
Happy coding 😉
Recommended posts
- Loop programming exercises index.
- C program to count number of digits in any number.
- C program to find sum of first and last digit of any number.
- C program to swap first and last digit of any number.
- C program to print multiplication table of any number.
- C program to find frequency of each digit in given number.
- C program to print number in words.