C Program to Swap Values of Two Variables Without Using a Third Variable तीसरे वेरिएबल का प्रयोग किए बिना दो वेरिएबल्स की वैल्यू स्वैप करने का प्रोग्राम
In C language, swapping means exchanging the values of two variables. We can swap two numerical variables without using a third variable by applying addition and subtraction operations.
सी लैंग्वेज में स्वैपिंग का अर्थ दो वेरिएबल्स की वैल्यू को आपस में बदलना होता है। जोड़ तथा घटाव की गणितीय क्रियाओं का प्रयोग करके तीसरे वेरिएबल के बिना भी दो संख्यात्मक वेरिएबल्स की वैल्यू स्वैप की जा सकती है।
C Program
#include <stdio.h>
int main(void)
{
float a, b;
printf("Enter two values:\n");
scanf("%f %f", &a, &b);
printf("Before swapping: a = %.2f, b = %.2f\n", a, b);
a = a + b;
b = a - b;
a = a - b;
printf("After swapping: a = %.2f, b = %.2f\n", a, b);
return 0;
}Output
Enter two values:
10 20
Before swapping: a = 10.00, b = 20.00
After swapping: a = 20.00, b = 10.00Explanation
व्याख्या
Suppose a = 10 and b = 20. The following operations swap their values:
मान लीजिए a = 10 तथा b = 20 हैं। निम्न ऑपरेशन्स उनकी वैल्यू को आपस में बदलते हैं:
Step 1:
a = a + b;Now, a = 30 and b = 20.
अब a = 30 तथा b = 20 हो जाते हैं।
Step 2:
b = a - b;Now, a = 30 and b = 10.
अब a = 30 तथा b = 10 हो जाते हैं।
Step 3:
a = a - b;Now, a = 20 and b = 10.
अब a = 20 तथा b = 10 हो जाते हैं।
Thus, the values of a and b are exchanged without using a third variable.
इस प्रकार तीसरे वेरिएबल का प्रयोग किए बिना a तथा b की वैल्यू आपस में बदल जाती हैं।
Note: This method can cause overflow for integer types or loss of precision for floating-point values. In practical programs, using a temporary variable is generally safer and clearer.
Comments
Post a Comment