MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

C++ Program to Swap Two Numbers Using Reference with Explanation

C++ Medium Functions 41 views
This problem helps you practice core C++ fundamentals in a practical way. It builds intuition around two, reference, swap. Let’s break it down step by step so you can implement it confidently.
Back to Questions

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.

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 Logic

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.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
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; }

Output Example

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

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next