Slider

C++ Program to Swap Values of Two Variables.

Here in this post, we are going to discuss two different methods to swap numbers. Using a third variable. Without using a third variable. C++ Code

In this post, we will learn how to swap the values of two numbers in the C++ programming language. Here in this post, we are going to discuss two different methods to swap numbers. 

  • Using a third variable.
  • Without using a third variable.

Approach 1: Using a third variable.

We are going to use one temporary variable which will copy the value of the first variable and then we will copy the value of the second variable into the first variable and at the end, we will copy the value of the temp variable into the second variable.

Let's understand with one Example:
Given:
Values before swapping:
first = 10  and second = 20 

Explanation:
temp = first = 10
first = second = 20
second  = temp = 10

Values after swapping:
second = 10 and first = 20

Below is C++ Code Implementation: 
//C++ Code to swap two number using temp
#include<iostream>
using namespace std;

int main(){
   
   int a = 10, b = 20;
   int temp;

   cout<<"Before swapping"<<endl;
   cout<<"a = "<<a<<" b = "<<b<<endl;

   //swapping using temp
   temp = a;
   a = b;
   b = temp;

   cout<<"After swapping"<<endl;
   cout<<"a = "<<a<<" b = "<<b<<endl;

   return 0;
}
Output:
Before swapping
a = 10 b = 20
After swapping
a = 20 b = 10

Approach 2: Without using a third variable.

To swap the values of two variables without using any temporary variable we need to do some mathematical calculations with the given two numbers.

Let's understand with one Example:
Given:
Values before swapping:
a = 10  and b = 20 

Explanation:
a = a + b = 10 + 20 = 30
b = a - b = 30 - 20 = 10
a = a - b = 30 - 10 = 20

Values after swapping:
b = 10 and a = 20

Below is the C++ Code Implementation:
//C++ Code to swap two number without using temp
#include<iostream>
using namespace std;

int main(){
   
   int a = 10, b = 20;
   int temp;

   cout<<"Before swapping"<<endl;
   cout<<"a = "<<a<<" b = "<<b<<endl;

   //swapping without using temp
   a = a + b;
   b = a - b;
   a = a - b;

   cout<<"After swapping"<<endl;
   cout<<"a = "<<a<<" b = "<<b<<endl;

   return 0;
}
Output:
Before swapping
a = 10 b = 20
After swapping
a = 20 b = 10

Next:


0

No comments

Post a Comment

both, mystorymag

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson
Table of Contents