a = a + b;
b = a - b;
a = a - b;
Input: 1 3
Output: 3 1
#AbdurRahimRatulAliKhan #Programming #Swapping #Algorithm
This code demonstrates how to swap two variables without using a third variable. The variables 'a' and 'b' are initially assigned the values from the input.
The swapping logic is achieved through the following steps:
1. The value of 'a' is updated by adding 'b' to it: `a = a + b;`
2. Then, 'b' is assigned the new value by subtracting the original value of 'b' from the updated 'a': `b = a - b;`
3. Finally, 'a' is updated with the new value by subtracting the updated 'b' (which is now the original value of 'a') from the updated 'a': `a = a - b;`
After the execution of these steps, the values of 'a' and 'b' are successfully swapped without using a third variable.
Example Input: 1 3
Step-by-step Execution:
a = 1, b = 3
# Step 1: a = a + b => a = 1 + 3 = 4
a = 4, b = 3
# Step 2: b = a - b => b = 4 - 3 = 1
a = 4, b = 1
# Step 3: a = a - b => a = 4 - 1 = 3
a = 3, b = 1
Example Output: 3 1
This code provides an efficient way to swap two variables using simple arithmetic operations, without the need for a third temporary variable. The algorithm is commonly used in programming to exchange the values of variables efficiently.