C++ Program to Swap Two Numbers using Third variable
Here we will see a program to swap two numbers using a temporary third variable. The steps are as follows:
1. User is asked to enter the value of first and second number. The input values are stored in first(num1) and second(num2) variable.
2. Assigning the value of first variable to the third variable.
3. Assigning the value of second variable to the first variable.
1. User is asked to enter the value of first and second number. The input values are stored in first(num1) and second(num2) variable.
2. Assigning the value of first variable to the third variable.
3. Assigning the value of second variable to the first variable.
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.4. Assigning the value of third variable to the second variable.
There are two ways to create a C++ 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 −
C++ Program to Swap Two Numbers using temp Variable
The program to swap two numbers using a temp variable is as follows.
Source Code:
#include<iostream> using namespace std; int main() { int a,b,temp; cout<<"\nEnter two numbers : "; cin>>a>>b; temp=a; a=b; b=temp; cout<<"\nAfter swapping numbers are : "; cout<<a<<" "<<b; return 0; }
2- C++ Program to Swap Two Numbers Without Using a Third Variable
The program to swap two numbers without using a third variable is as follows −
#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.
Post a Comment