Challenge: Swap Two Values

Lab C++ Beginner 10 points

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
Sample output available
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
HOME LABS COMMUNITY DASHBOARD