C++ program to Swap two numbers

Google Advertisements

Prev Tutorial Next Tutorial

C++ program to Swap two numbers

Once again we discuss about one of the most basic and important C++ Programs which is frequently ask in any interview or exam. To write swap two numbers program in C++ is very simple and easy just you need 3 variable and = operator. Swap numbers means exchange the values of two variables with each other. For example variable num1 contains 200 and num2 contains 400 after swap there values num1 contains 400 and num2 contains 200.

Example: Suppose we have three glass A, B, Temp. Glass A contain ball printed 30, Glass B contain ball printed 50 and Glass Temp is empty now we want to interchange these two glass (A, B) ball. So we follow below steps...

  • First we take Glass A and there ball 30 place inside Glass Temp
  • Now Glass A is empty, take Glass B and there ball 50 place inside Glass A.
  • Now Glass B is empty, take Glass Temp and there ball 30 place inside Glass B
  • Finally Both Glass values are exchange, Glass A contain ball 50 and Glass B contain ball 30.
swap two numbers program in c++

Swap two numbers using third variables

Swap Two Numbers Program in C++

#include<iostream.h>
#include<conio.h>

void main()
{
int a,b,c;
clrscr();
cout<<"Enter value of a: ";
cin>>a;
cout<<"Enter value of b: ";
cin>>b;
c=a;
a=b;
b=c;
cout<<"After swap a: "<<a<<"b: "<<b;
getch();
}

Output

Enter value of a: 10
Enter value of b: 20
After swap a: 20 b: 10

Swap two numbers without using third variable

Swap 2 Numbers Program in C++

#include<iostream.h>
#include<conio.h>

void main()
{
int a,b;
clrscr();
cout<<"Enter value of a: ";
cin>>a;
cout<<"Enter value of b: ";
cin>>b;
a=a+b;
b=a-b;
a=a-b;
cout<<"After swap a: "<<a<<"b: "<<b;
getch();
}

Output

Enter value of a: 10
Enter value of b: 20
After swap a: 20 b: 10

Prev Tutorial Next Tutorial

Google Advertisements

Buy This Ad Space @$50 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 8076671483

Pure VPN Privide Lowest Price VPN Just @ $1.65. Per Month with Non Detected IP Lowest Price Non Detected IP VPN

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

Cloud computing is the on demand availability of computer system resources, especially data storage and computing power, without direct active management by the user. Cloud Computing Tutorial

College Projects Related to Java, AWT, C Projects for College, C++ Projects for College, Android Projects. Download Java C C++ Projects

Download Projects

Adsense Advertisements


Buy This ads Space 8076671483

Buy This Ad Space @$120 per Month, Ad Size 300X600 Contact on: hitesh.xc@gmail.com or 8076671483 Try this Keyword C++ Programs