Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Printing the numbers in reverse order using Division and modulo operators using C
In C programming, we can reverse a number using division and modulo operators without using any predefined functions. This approach extracts individual digits from a number and reconstructs them in reverse order.
Syntax
int digit = number % 10; // Extract last digit int remaining = number / 10; // Remove last digit
How It Works
The logic to reverse a number using mathematical operators is −
- Modulo operator (%): Extracts the last digit of a number
- Division operator (/): Removes the last digit by integer division
- Extract digits from right to left and reconstruct the number from left to right
Example 1: Reversing a 2-Digit Number
This example demonstrates how to reverse a 2-digit number using division and modulo operators −
#include <stdio.h>
int main() {
int number;
printf("Enter a 2-digit number: ");
scanf("%d", &number);
int firstDigit = number % 10; // Extract last digit
int secondDigit = number / 10; // Extract first digit
printf("Original number: %d
", number);
printf("Reversed number: %d%d
", firstDigit, secondDigit);
return 0;
}
Enter a 2-digit number: 45 Original number: 45 Reversed number: 54
Example 2: Reversing a 3-Digit Number
For a 3-digit number, we need to extract three digits and reconstruct them in reverse order −
#include <stdio.h>
int main() {
int number, digit1, digit2, digit3, reversed;
printf("Enter a 3-digit number: ");
scanf("%d", &number);
digit1 = number / 100; // Extract hundreds digit
digit2 = (number % 100) / 10; // Extract tens digit
digit3 = number % 10; // Extract units digit
reversed = 100 * digit3 + 10 * digit2 + digit1;
printf("Original number: %d
", number);
printf("Reversed number: %d
", reversed);
return 0;
}
Enter a 3-digit number: 479 Original number: 479 Reversed number: 974
Key Points
- The modulo operator (%) gives the remainder when dividing by 10, effectively extracting the last digit
- Integer division by 10 removes the last digit from the number
- This method works for any fixed-length number by applying the pattern systematically
Conclusion
Using division and modulo operators provides an efficient way to reverse numbers in C. This mathematical approach demonstrates fundamental digit manipulation techniques without requiring string operations or library functions.
Advertisements
