## C Program to Reverse a Number

Last Updated On
Saturday 21st May 2022

## c program reverse number

We can reverse a number in c using loop and arithmetic operators.For Example , you take the number 12345, the reverse is 54321.

Let’s see how the while loop works

• For Example: Given Input is 12345. The required output is 54321. Let us assume , our reversed number (reverse) is 0.
• Multiply the reverse number with 10 and add the digit which we extracted from the input.
• Equate the reverse with result
Number Remainder Reverse
12345 5 0 * 10 + 5 = 5
2345 4 5 * 10 + 4 = 54
345 3 54 * 10 + 3 = 543
45 2 543 * 10 + 2 = 5432
5 1 5432 * 10 + 1 = 54321
Loop Terminates

In Simple

• Initialize reverse = 0
• For every digit in the number , reverse = reverse * 10 + remainder
• Output the reverse.
	#include<stdio.h>
int main(){
int number = 12345;
int reverse = 0;
while(number != 0){
reverse = reverse * 10 + number % 10;
number /= 10;
}
printf("%d", reverse);
}



Here

• We use the Modulo operator (%) to get remainder.
• We use the Division Operator (/) to get quotient.

Output

	54321



Let user enters the input number.

	#include<stdio.h>
int main(){
int number;
printf("Enter an integer: ");
scanf("%d", &number);
int reverse = 0;
while(number != 0){
reverse = reverse * 10 + number %10;
number /= 10;
}
printf("Reversed number : %d", reverse);
}



Output

	Enter an integer: 12345678
Reversed number : 87654321



Finally, the reverse variable is printed on the screen.

c program to reverse a number
c programming reverse number
how to reverse a number