C Program to Reverse a Number
This program takes an integer input from the user and reverses its digits using basic arithmetic operations.
Concept Overview
To reverse a number, we repeatedly extract its last digit using the modulus operator (%) and build the reversed number step by step by multiplying the current reversed number by 10 and adding the last digit.
Program
C
#include <stdio.h>
int main() {
int num, reversed = 0, remainder;
printf("Enter a number: ");
scanf("%d", &num);
while(num != 0) {
remainder = num % 10;
reversed = reversed * 10 + remainder;
num /= 10;
}
printf("Reversed number = %d\n", reversed);
return 0;
}
Output
Enter a number: 12345 Reversed number = 54321
Explanation
- The last digit of the number is obtained using `num % 10`.
- The reversed number is built as `reverse = reverse * 10 + remainder`.
- The original number is reduced each iteration using `num = num / 10`.
- The process repeats until the number becomes 0.
Note: Note: This program works for positive integers. For negative numbers, handle the sign separately if required.
Codecrown