write an algorithm flowchart c++ program to swap 2 number by using 3rd variable
Answers
Answered by
0
include <iostream> using namespace std; int main() { int a = 5, b = 10, temp; cout << "Before swapping." << endl; cout << "a = " << a << ", b = " << b << endl; temp = a; a = b; b = temp; cout << "\nAfter swapping." << endl; cout << "a = " << a << ", b = " << b << endl; return 0;
Output
Before swapping. a = 5, b = 10 After swapping. a = 10, b = 5
To perform swapping in above example, three variables are used.
The contents of the first variable is copied into the temp variable. Then, the contents of second variable is copied to the first variable.
Finally, the contents of the temp variable is copied back to the second variable which completes the swapping process.
You can also perform swapping using only two variables as below.
iostream> using namespace std; int main() { int a = 5, b = 10; cout << "Before swapping." << endl; cout << "a = " << a << ", b = " << b << endl; a = a + b; b = a - b; a = a - b; cout << "\nAfter swapping." << endl; cout << "a = " << a << ", b = " << b << endl; return 0; }
The output of this program is same as first program above.
* Hope its helpful to you if yes then mark this answer as brainliest and follow me for more answers*
Output
Before swapping. a = 5, b = 10 After swapping. a = 10, b = 5
To perform swapping in above example, three variables are used.
The contents of the first variable is copied into the temp variable. Then, the contents of second variable is copied to the first variable.
Finally, the contents of the temp variable is copied back to the second variable which completes the swapping process.
You can also perform swapping using only two variables as below.
iostream> using namespace std; int main() { int a = 5, b = 10; cout << "Before swapping." << endl; cout << "a = " << a << ", b = " << b << endl; a = a + b; b = a - b; a = a - b; cout << "\nAfter swapping." << endl; cout << "a = " << a << ", b = " << b << endl; return 0; }
The output of this program is same as first program above.
* Hope its helpful to you if yes then mark this answer as brainliest and follow me for more answers*
Similar questions