CodesJava

Easy learning with example program codes

CPP program to swap two numbers


The below program is to swap two numbers with and without using third variable. The CPP cout object is used to output the result on the screen. Swapping two numbers simply means interchanging the values of two numeric variables.

Before Swapping,

A = n1

B = n2

After Swapping,

A = n2

B = n1

Code:

#include <iostream.h>
using namespace std;
 
int main()  
{  
int a=1, b=2;
int temp;
 
cout << "Before Swapping:\na = " << a << "\nb = " << b << endl;  
 
temp = a;  
a = b;  
b = temp;  
 
cout << "After Swapping:\na = " << a << "\nb = " << b;  
return 0;
}

Output

Before Swapping:
a = 1
b = 2
After Swapping:
a = 2
b = 1
Please follow and like us:
Posted in CPP   


Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki