Lecture No:3 | 28-0202025| C++ Program to Swap Two Variables Using a Third Variable (c)
INPUT OF THE CODE:
Step : 1
First we will write some libraries which will execute our program which will be necessary to run the program. After that we will start writing our program inside the main function to run the program.
Include libraries
using namespace std;
Step : 2
First of all we will take three variables AB and C. In variable A we will store 20 values and in B we will store 10 values and we will leave C black and will not store any value in it.
int a = 20, b = 10, c;
Step : 3
Before swapping the values, we will use Cout to see the values of A and B, which will allow the user to see which value is present in A and B first.
cout << "Before swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
Step : 4
Now we will apply a logic that will equal the C variable we have to A. In this way, the value inside A will be stored in the C variable and the B variable will be empty.
c=a;
Step : 5
Then we will make A equal to B, so that the value store inside B will be moved to A and B will be empty.
a=b;
Step : 6
Now we will make B equal to C, in this way the value present in C will be added to B and C will become empty, in this way we will change both the values and the values of A and B that we have will be swapped, the value of A will be stored in B and the value of B will be stored in A.
b=c;
Step : 7
After that, we will use Cout which will show us the new values of A and B that we have created as output.
cout << "After swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
OUTPUT OF CODE:
Cc:
@suboohi