C Program to Reverse a Number किसी संख्या को Reverse करने का C प्रोग्राम
Reversing a number means writing its digits in the opposite order. For example, the reverse of 1234 is 4321.
किसी संख्या को Reverse करने का अर्थ उसके अंकों को उल्टे क्रम में लिखना होता है। उदाहरण के लिए, 1234 का Reverse 4321 होगा।
C Program
#include <stdio.h>
int main(void) {
int n, q, r, rev = 0;
printf("Enter an integer number:\n");
if (scanf("%d", &n) != 1) {
printf("Invalid input! Please enter an integer.\n");
return 1;
}
if (n < 0) {
printf("Please enter a non-negative integer.\n");
return 1;
}
q = n;
while (q != 0) {
r = q % 10;
q = q / 10;
rev = rev * 10 + r;
}
printf("Reverse of given number %d = %d\n", n, rev);
return 0;
}Sample Output 1
Enter an integer number:
12345
Reverse of given number 12345 = 54321Sample Output 2
Enter an integer number:
1200
Reverse of given number 1200 = 21Explanation
Let us understand the program with the number 1234.
The program uses the modulus operator (%) to extract the last digit and integer division (/) to remove the last digit. The extracted digit is added to the reversed number using the formula:
[ rev = rev*10 + r ]
| Step | q | r = q % 10 | rev = rev * 10 + r |
|---|---|---|---|
| 1 | 1234 | 4 | 4 |
| 2 | 123 | 3 | 43 |
| 3 | 12 | 2 | 432 |
| 4 | 1 | 1 | 4321 |
Therefore, the reverse of 1234 is 4321.
प्रोग्राम में Modulus Operator (%) की सहायता से संख्या का अंतिम अंक प्राप्त किया जाता है तथा Integer Division (/) से उस अंक को मूल संख्या से हटा दिया जाता है। इसके बाद प्राप्त अंक को rev में जोड़ने के लिए निम्न Formula का उपयोग किया जाता है:
[
rev = rev \times 10 + r
]
यह प्रक्रिया तब तक दोहराई जाती है जब तक मूल संख्या q का मान 0 नहीं हो जाता।
Modern C Compatibility Note
This program uses standard C and works with modern compilers such as GCC, Clang, and Visual Studio C. It does not require conio.h, clrscr(), or getch().
This program demonstrates how to reverse a number using a while loop, modulus operator (%), and integer division (/).
यह प्रोग्राम while लूप, Modulus Operator (%) और Integer Division (/) की सहायता से किसी संख्या को Reverse करना सिखाता है।
Comments
Post a Comment