⑫ C Program to Swap Two Numbers Without Using a Temporary Variable (With Program and Explanation)
๐ C Program to Swap Two Numbers Without Using a Temporary Variable
Swapping two numbers means exchanging their values.
Usually, we use a temporary variable, but in this program, we’ll swap the numbers without using any extra variable.
๐ก Logic Used
We use addition and subtraction to swap the values.
Steps:
-
Add both numbers and store the result in the first number.
-
Subtract the second number from the first to get the original first number.
-
Subtract the new first number from the second to get the original second number.
๐ง Algorithm
-
Start
-
Read two numbers
aandb -
a = a + b -
b = a - b -
a = a - b -
Print swapped values
-
End
๐ป C Program Code
๐ Example Output
Input
Output
๐ Conclusion
This program demonstrates how two numbers can be swapped without using a temporary variable using simple arithmetic operations. It is commonly asked in C interviews and exams.
Comments
Post a Comment