The reverse of a number of means reversing the order of digits of a number. In this article, we will learn how to reverse the digits of a number in C language.
Example:
Input: 12354
Output: 45321
Explanation: The number 12354 when reversed gives 45321Input: 623
Output: 326
Explanation: The number 623 when reversed gives 326.
Reverse a Number in C
The simplest method to reverse a string is by extracting its digits one by one using (%) modulo and (/) division operator and form the number by rearrange them in the reverse.
#include <stdio.h>
// Iterative function to
// reverse digits of num
int reverseDigits(int num)
{
int rev_num = 0;
while (num > 0) {
rev_num = rev_num * 10 + num % 10;
num = num / 10;
}
return rev_num;
}
int main()
{
int num = 4562;
printf("Given number: %d\n", num);
printf("Revers of the number: %d",
reverseDigits(num));
getchar();
return 0;
}
Output
Reverse of no. is 2654
Explanation
The above program use a while loop to iterate until the value of num becomes 0. Inside the loop, the last digit of num is extracted using the modulo operator (num % 10). This digit is then added to rev_num after multiplying it by 10, which means the existing digits of rev_num are shifted one place to the left.
The value of num is updated by dividing it by 10, (num = num / 10). This removes the last digit of num in each iteration, and terminates the loop when num becomes 0.
num = 4562
rev_num = 0
rev_num = rev_num *10 + num%10 = 2
num = num/10 = 456
rev_num = rev_num *10 + num%10 = 20 + 6 = 26
num = num/10 = 45
rev_num = rev_num *10 + num%10 = 260 + 5 = 265
num = num/10 = 4
rev_num = rev_num *10 + num%10 = 2650 + 4 = 2654
num = num/10 = 0