C++ program to Swap two numbers


Prev Tutorial Next Tutorial

C++ program to Swap two numbers

Swap numbers means exchange the values of two variables with each other. For example variable num1 contains 20 and num2 contains 40 after swap there values num1 contains 40 and num2 contains 20.

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

  • First we take Glass A and there values place inside Glass Temp
  • Now Glass A is empty, take Glass B and there values place inside Glass A.
  • Now Glass B is empty, take Glass Tempa and there values place inside Glass B
  • Finall Both Glass values are exchange, Glass A contain 50 and Glass B contain 30.
swapping two numbers

Swap two numbers using third variables

Example

#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

Example

#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

Advertisements




Facebook Likes

Advertisements