C++ Program To Swap Two Number Without Third Variable

Swap Two Number Without Third Variable.

C++ Program To Swap Two Number Without Third Variable.

Logi used to swap two numbers.

  first number = first number  +  second number;
    second number = first number  -  second number;
    first number = first number  -  second number;

Program

#include<iostream.h>
#include<conio.h>
void main()
{
int a=5,b=10;
clrscr();
cout<<"Value of a before Swaping:- "<<a<<endl;
cout<<"Value of b before Swaping:- "<<b<<endl;
a=a+b;
b=a-b;
a=a-b;
cout<<"Value of a after Swaping:- "<<a<<endl;
cout<<"Value of b after Swaping:- "<<b<<endl;
getch();
}

OUTPUT:-

Swap Two Number Without Third Variable


Swap two numbers using single inheritance.

#include<iostream.h>
#include<conio.h>
class scan
{
 protected:
 int x,y;
 public:
 void get()
 {
  cout<<"Enter value of x:- ";
  cin>>x;
  cout<<"Enter value of y:- ";
  cin>>y;
 }
};
class swap:public scan
{
 public:
 void swap_val()
 {
    x=x+y;
    y=x-y;
    x=x-y;
 }
 void display()
 {
  cout<<"Value of x:- "<<x<<endl;
  cout<<"Value of y:- "<<y;
 }
};
void main()
{
 clrscr();
 swap s1;
 s1.get();
 s1.swap_val();
 cout<<"................................"<<endl;
 s1.display();
 getch();
}

OUTPUT

Swap Two Number Without Third Variable


Comment below if you are facing any problem.


Also read

C++ Program to find reverse of a input number
C++ Program to Print a Fibonacci series
C++ Program to count no. of digits in the input


Summary
C++ Program To Swap Two Number Without Third Variable
Article Name
C++ Program To Swap Two Number Without Third Variable
Description
This Program illustrate the concept To Swap Two Number Without Third Variable.
Author
Publisher Name
Scanfcode
Publisher Logo

Leave a Reply

Your email address will not be published. Required fields are marked *