Write a function that swaps the values of the two variables using third variable called as temporary variable.
For example:
If A=5 and B=6 , after swapping the variables should have values as A=6 and B=5.
Method 1:
Implementation:
Enter value 1: 5
Enter value 2: 6
Before Swapping:
Value1=5 Value2=6
After Swapping:
Value1=6 Value2=5
Method 2:
Swapping the values of two variables can be done, without using a third variable also, using the following method.
Implementation:
Output:
Enter the value of a: 5
Enter the value of b: 6
Before swapping:
a=5 b=6
After swapping:
a=6 b=5
For example:
If A=5 and B=6 , after swapping the variables should have values as A=6 and B=5.
Method 1:
1. Copy the value of A to the temporary variable, say temp. Now, A=5, B=6, temp=5
2. Copy the value of B to A. A=6, B=6, temp=5
3. Copy the value of temp to B. A=6, B=5, temp=5
4. Now the variables A & B has the swapped values.
Implementation:
Output:
Enter value 1: 5
Enter value 2: 6
Before Swapping:
Value1=5 Value2=6
After Swapping:
Value1=6 Value2=5
Method 2:
Swapping the values of two variables can be done, without using a third variable also, using the following method.
Where a and b are the two numbers whose values should be swapped(Exchanged) between each other.a=a+b;
b=a-b;
a=a-b;
Implementation:
Output:
Enter the value of a: 5
Enter the value of b: 6
Before swapping:
a=5 b=6
After swapping:
a=6 b=5