
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ Program to Swap Two Numbers
There are two ways to create a program to swap two numbers. One involves using a temp variable and the second way does not use a third variable. These are explained in detail as follows −
Program to Swap Two Numbers using temp Variable
The program to swap two numbers using a temp variable is as follows.
Example
#include <iostream > using namespace std; int main() { int a = 10, b = 5, temp; temp = a; a = b; b = temp; cout<<"Value of a is "<<a<<endl; cout<<"Value of b is "<<b; return 0; }
Output
Value of a is 5 Value of b is 10
In the above program, there are two variables a and b that store the two numbers. First, the value of a is stored in temp. Then, the value of b is stored in a. Lastly, the value of temp is stored in b. After this, the values in a and b are swapped.
temp = a; a = b; b = temp;
Then the values of a and b are displayed.
cout<<"Value of a is "<<a<<endl; cout<<"Value of b is "<<b;
Program to Swap Two Numbers Without Using a Third Variable
The program to swap two numbers without using a third variable is as follows −
Example
#include <iostream> using namespace std; int main() { int a = 10, b = 5; a = a+b; b = a-b; a = a-b; cout<<"Value of a is "<<a<<endl; cout<<"Value of b is "<<b; return 0; }
Output
Value of a is 5 Value of b is 10
In the above program, first the sum of a and b is stored in a. Then, the difference of a and b is stored in b. Finally, the difference of a and b is stored in b. At the end of this, the values in a and b are swapped.
a = a+b; b = a-b; a = a-b;
Then the values of a and b are displayed.
cout<<"Value of a is "<<a<<endl; cout<<"Value of b is "<<b;
- Related Articles
- Java Program to Swap Two Numbers.
- Haskell Program to Swap Two Numbers
- Kotlin Program to Swap Two Numbers
- Swap two numbers in C#
- 8085 program to swap two 8-bit numbers
- How to Swap Two Numbers in Swift Program?
- C program to swap two strings
- Java program to swap two numbers using XOR operator
- How to Swap Two Numbers in Golang?
- 8085 program to swap two 8 bit numbers using Direct addressing mode
- 8085 program to swap two 16-bit numbers using Direct addressing mode
- Java program to swap two integers
- Write a Golang program to swap two numbers without using a third variable
- How to swap two numbers without using a temp variable in C#
- C++ Program to Swap Numbers in Cyclic Order Using Call by Reference
