C++ Program for Number Swapping

A Few days back when I was in Delhi, one student asked me how to write a c Plus Plus program to swap two numbers by using the temp variable. I had make understand the logic behind this program to that student and said I will write this program for you.

This is a very simple & easy C++ (C Plus Plus) program for number swapping. In the below program, we swapped two numbers using the temporary variable.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#include <iostream>

usingnamespacestd;

intmain()

{

intx=5,y=10,temp;

cout<<"Before swapping."<<endl;

cout<<"x = "<<x<<", y = "<<y<<endl;

temp=x;

x=y;

y=temp;

cout<<"\nAfter swapping."<<endl;

cout<<"x = "<<x<<", y = "<<y<<endl;

return0;

}

Swap two numbers without using third variable

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

#include<iostream.h>

#include<conio.h>

voidmain()

{

inta,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 is:

Before swapping. x = 15, y = 10 After swapping. x = 10, y = 15

Share this post:

Related Tutorials

About: Prem Tiwari

Prem Tiwari is the founder of FreeWebMentor.com and also a professional developer who has vast experience in PHP and open source technologies. Apart from this, he is a blogger by hobby and also he has been a regular speaker of WordPress sessions in various IT Companies. View all posts by Prem Tiwari

Subscribe my updates via Email

We use cookies to ensure that we give you the best experience and deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.OkPrivacy policy