codescracker


c++

C++ Program to Swap Two Numbers



« Previous Program Next Program »


Swap Two Numbers in C++

To swap two numbers in C++ programming, you have to first ask to the user to enter the two number, and store both the number in the variable say num1 and num2. Now to swap both the number, first, make a variable say swap of same type. Now place first number in the swap, then place second number in the first, and then place swap in the second. After swapping the two number, print it on the screen as shown here in the following program.

C++ Programming Code to Swap Two Numbers

Following C++ program ask to the user to enter the two number to swap them and display the output on the screen :

/* C++ Program - Swap Two Numbers */
		
#include<iostream.h>
#include<conio.h>
void main()
{
	clrscr();
	int num1, num2, swap;
	cout<<"Enter two number : ";
	cout<<"\nFirst Number : ";
	cin>>num1;
	cout<<"Second Number : ";
	cin>>num2;
	swap=num1;
	num1=num2;
	num2=swap;
	cout<<"The value of first and second number after swapping is \n";
	cout<<"First Number = "<<num1<<"\n"<<"Second Number = "<<num2;
	getch();
}

When the above C++ program is compile and executed, it will produce the following result:

C++ program to swap two numbers

Same Program in Other Language

You may like the same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test