Challenge: Swap Two Values
Completed
You have int a = 4; and int b = 9;. Swap their values using a third variable, then print a = 9, b = 4.
Input
None.
Output
One line: a = 9, b = 4
Example
Output
a = 9, b = 4
Editor
C++
Hints
If you do a = b first, the old value of a is lost.
Save a in temp, then a = b, then b = temp.
Solution explanation
Like swapping the drinks in two glasses, you need a third, empty glass to hold one of them for a moment.
Show solution
#include <iostream>
using namespace std;
int main() {
int a = 4;
int b = 9;
int temp = a;
a = b;
b = temp;
cout << "a = " << a << ", b = " << b << "\n";
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module