Swap Two Values without Third Variable In C

#include <stdio.h>
int main() {
int a, b ;
// Ask user to enter two numbers
printf("Enter Value of a & b: ");
scanf("%d%d", &a,&b);
// Add the two numbers
a = a + b ;
b = a - b ;
a = a - b ;
// Display the result
printf("value after Swap of : a=%d and b=%d",a,b);
return 0;
}
Detailed Explanation:
Initial Input:
- The program prompts the user to enter two integer values for
aandb. - Example: Suppose the user enters
a = 5andb = 3.
- The program prompts the user to enter two integer values for
Step-by-Step Execution:
- Step 1:
a = a + b;- This calculates the sum of
aandband stores it ina. - For
a = 5andb = 3, it becomesa = 5 + 3 = 8.
- This calculates the sum of
- Step 2:
b = a - b;- This calculates the original value of
aby subtracting the current value ofbfrom the current value ofa. - For
a = 8andb = 3, it becomesb = 8 - 3 = 5.
- This calculates the original value of
- Step 3:
a = a - b;- This calculates the original value of
bby subtracting the current value ofb(which is now the original value ofa) from the current value ofa. - For
a = 8andb = 5, it becomesa = 8 - 5 = 3.
- This calculates the original value of
- Step 1:
Final Values:
- After these operations, the values of
aandbare swapped. ais now3andbis now5.
- After these operations, the values of
Output:
- The program prints the swapped values.
- The output will be:
value after Swap of : a=3 and b=5.
Example Run:
Enter Value of a & b: 5 3
value after Swap of : a=3 and b=5
This method of swapping values works by manipulating the sums and differences of the variables, effectively exchanging their values without the need for a temporary storage variable.
0 Comments