Tutorialspoint
Problem
Solution
Submissions

Swap Two Numbers

Certification: Basic Level Accuracy: 60.58% Submissions: 104 Points: 5

Write a C++ program that swaps two numbers using pointers.

Example 1
  • Input: a = 5, b = 10
  • Output: a = 10, b = 5
  • Explanation:
    • Step 1: Declare pointers for variables a and b.
    • Step 2: Use pointers to access and swap the values.
    • Step 3: After swapping, a = 10 and b = 5.
Example 2
  • Input: a = -3, b = 7
  • Output: a = 7, b = -3
  • Explanation:
    • Step 1: Declare pointers for variables a and b.
    • Step 2: Use pointers to access and swap the values.
    • Step 3: After swapping, a = 7 and b = -3.
Constraints
  • The values of a and b are integers
  • Use pointers to swap the values
  • Time Complexity: O(1)
  • Space Complexity: O(1)
ArraysPointers and ReferencesAmazonFacebook
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use pointers to access the memory locations of the variables.
  • Swap the values stored at the memory locations using a temporary variable.
  • Ensure that the original variables are modified after the swap.

Steps to solve by this approach:

 Step 1: Define a function swap_numbers that takes two integer pointers as parameters.

 Step 2: Use a temporary variable to store the value at the first pointer's address.
 Step 3: Assign the value at the second pointer's address to the first pointer's address.
 Step 4: Assign the temporary value to the second pointer's address.
 Step 5: In main, declare two integer variables and initialize them.
 Step 6: Call swap_numbers with the addresses of these variables.
 Step 7: Print the swapped values to verify the operation.

Submitted Code :