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
Posted in CPP   
Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

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