Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to swap the values of two variables

C++ Code Example — Function Programs

ADVERTISEMENT

WAP to swap the values of two variables

Objective

Write a C++ program to swap the values of two variables using a function.

Algorithm / Approach

  1. Declare a swap(int, int) function prototype.
  2. Read two variables in main() and print them.
  3. Call the swap(x, y) function, passing the variables.
  4. Inside the function, swap the values using a temporary variable and print them.
main.cpp
#include<iostream>
using namespace std;
void swap(int, int);
int main( ){
 int x,y;
 cout<<"Enter X: ";
 cin>>x;
 cout<<"Enter Y: ";
 cin>>y;
 cout<<"\nBEFORE SWAP:\n";
 cout<<"X = "<< x<<" and Y = "<< y;
 swap(x,y);
 return 0;
}
void swap(int x, int y){
 int temp = x;
 x = y;
 y = temp;
 cout<<"\n\nAFTER SWAP : \n";
 cout<<"X= "<< x<<" and Y= "<< y;
}

Expected Output

Enter X: 15
Enter Y: 20

BEFORE SWAP:
X=15 and Y=20

AFTER SWAP:
X=20 and Y=15

Explanation of the Program

  • Functions allow you to break down your code into reusable, modular blocks.
  • Note: This program demonstrates "Pass by Value". The swap function receives completely independent *copies* of the variables. While the copies are successfully swapped inside the function, the original variables back in main() remain completely unchanged!

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Assuming "Pass by Value" will modify original variables. To actually swap the variables in main, you must use "Pass by Reference" (e.g., void swap(int &x, int &y)) or pointers.
ADVERTISEMENT