Swap Two Numbers Using Reference

Swap Two Numbers Using Reference

Medium C++ Functions 40 views
Explanation Complexity

Problem Statement

Swap two variables using pass by reference.
Real Life: Like exchanging positions of two objects.

Input Format

Two integers a and b.

Output Format

Values of a and b after swapping.

Example

a = 10
b = 20
a = 20
b = 10

Constraints

• Use pass by reference

• No third variable restriction is optional

Concept Explanation

Pass by reference allows a function to work on the original variables,
so changes inside the function affect values in main().

Step-by-Step Explanation

1.Define a function swap(int &x, int &y).

2.References x and y point to original variables a and b.

3.Inside the function:

• Store x in a temporary variable.

• Assign y to x.

• Assign temporary value to y.

4.Function ends.

5.Values in main() are already swapped.

Concept Explanation

Pass by reference allows a function to work on the original variables,
so changes inside the function affect values in main().

Step-by-Step Explanation

1.Define a function swap(int &x, int &y).

2.References x and y point to original variables a and b.

3.Inside the function:

• Store x in a temporary variable.

• Assign y to x.

• Assign temporary value to y.

4.Function ends.

5.Values in main() are already swapped.

Input / Output Format

Input Format
Two integers a and b.
Output Format
Values of a and b after swapping.
Constraints
• Use pass by reference

• No third variable restriction is optional

Examples

Input:
a = 10 b = 20
Output:
a = 20 b = 10

Example Solution (Public)

C++
void swapNumbers(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}

void function_q9_pass_by_reference() {
    int x = 10, y = 20;
    
    cout << "Before swap: x = " << x << ", y = " << y << endl;
    swapNumbers(x, y);
    cout << "After swap: x = " << x << ", y = " << y << endl;
}

Official Solution Code

void swapNumbers(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}

void function_q9_pass_by_reference() {
    int x = 10, y = 20;
    
    cout << "Before swap: x = " << x << ", y = " << y << endl;
    swapNumbers(x, y);
    cout << "After swap: x = " << x << ", y = " << y << endl;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.