
477 views
Reverse Number in C
To reverse a number in C, you can repeatedly extract and print the last digit of the number by taking its remainder when divided by 10. After printing the last digit, you can remove it from the number by dividing it by 10. Repeat this process until the number becomes zero. Here’s a C program to reverse a number:
C
#include <stdio.h>
int main() {
int num, reversedNum = 0;
printf("Enter an integer: ");
scanf("%d", &num);
// Reverse the number
while (num != 0) {
int digit = num % 10; // Extract the last digit
reversedNum = reversedNum * 10 + digit; // Append the digit to the reversed number
num /= 10; // Remove the last digit
}
printf("Reversed number: %d\n", reversedNum);
return 0;
}In this program:
- We input an integer from the user.
- We initialize
reversedNumto 0, which will store the reversed number. - Inside a
whileloop, we repeatedly extract the last digit ofnumusing the modulo operator (%). This digit is stored in thedigitvariable. - We append the
digittoreversedNumby multiplyingreversedNumby 10 and adding thedigitto it. This effectively adds the digit to the reversed number. - We remove the last digit from
numby dividing it by 10. - We repeat this process until
numbecomes zero. - Finally, we print the
reversedNum, which contains the reversed digits of the input number.
Compile and run the program, and it will reverse the entered integer and display the reversed number.