# Swap two numbers in cpp

Swap two numbers in cpp  is simple program to swapping of two numbers in c++ using functions.

In this tutorial we will see What is swapping, how to swap two numbers and C++ program to swap two numbers using function.

What is swapping: Swapping of two numbers means replacing the numbers.

Their are two ways to swap two numbers using functions in c++

1. Call by value
2. Call by reference

Lets see methods

Call by value : When function are called by passing the value they are called as call  by value.

First we will see program to swap two numbers using function by method 1 (call by value)

## C++ Program To Swap Two Numbers Using Functions

Output :

Explanation :

1. First we declare the function which is swap function

=> void swap(int ,int );

2. Execution starts with the main method.

3. Declare the variables

a, b => to store two numbers

4. Take a input from user two numbers

=>  cin>>a>>b;   a = 10, b= 20

5. We print numbers before swapping.

6. Next we call function by passing value a and b .

swap(a,b);  => function get executed

swap(int x,int y) {   => x= 10 y = 20

z=x;   => z=10

x=y;  => x=20

y=z;  => y = 10

7. Now we print numbers after swapping

cout<<“x= “<<x<<” “<<“y= “<<y<<” \n”;

} => Returns to main function

8. End with the program.

Call by reference: When function are called by passing the address they are called as call  by reference.

we will see program to swap two numbers using function by method 2 (call by reference)

## Write a program to swap two numbers using function in c++

Output :

Explanation :

1. First we declare the function which is swap function

=> void swap(int *x ,int *y);

2. Execution starts with the main method.

3. Declare the variables

a, b => to store two numbers

4. Take a input from user two numbers

=>  cin>>a>>b;   a = 10, b= 20

5. We print numbers before swapping.

6. Next we call function by passing address of a and b

swap(&a,&b);  => function get executed

swap(int *x,int  *y) {   => x= 10 y = 20

*z=*x;   => *z=10

*x=*y;  => *x=20

*y=*z;  =>*y = 10

} => Returns to main function

7. Now we print numbers after swapping

cout<<“x= “<<x<<” “<<“y= “<<y<<” \n”;

8. End with the program.