×

Swap numbers in C++

Swap numbers

Swapping refers to interchanging values between two variables. Swapping is important and easy to understand programming logic in the world of coding. Though it is used in the programming only, in special cases, it can be another practice to solve problems that need some logical order.

For example: If we take two variables say A and B and assign them values 10 and 20 respectively. The values after swapping to, A=20 and B=10.

Let's discuss the logic behind it.

There are two methods of swapping numbers: with or without a third variable. Let the third variable be temp that can also be called 'temporary variable.'

A temporary variable is used to hold the values during interchanging values. This value is later passed onto other variables after the value is swapped.

Swapping using a temporary or third variable:

As discussed earlier, we can swap numbers in C++ with or without using a third variable. Let us first swap numbers by using a temporary variable.

#include<iostream>
 using namespace std;
 int main()
 {
 int a=10,b=20;  //initializing a & b with values
 int c;
 cout<<"Before Swapping: "<<a<<" "<<b<<" "<<endl;
 c=a;        //swapping operation
 a=b;
 b=c;
 cout<<"After Swapping:  "<<a<<" "<<b<<" "<<endl;
 return 0;
       } 

Output:

 Before Swapping: 10  20
 After Swapping:  20  10 

Explanation:

In the above code, we can clearly see that a temporary or a third variable c has been used to hold the values while swapping. Initially, a & b have been assigned values 10 and 20 respectively.

The next operation is to pass the value of a to variable c and then assign the value of b to a. Later the value of a which had 10 earlier now has 20 as value and b now has been assigned 10 by the third variable c.

Swapping without using a third variable:

Let us now discover how swapping can be performed without using a third variable.

The swapping operation can be performed without using third variables in two ways:

  1. Using * and /
#include<iostream>
 using namespace std;
 int main()
 {
 int a=10,b=20;
 cout<<"Before swapping: "<<a<<" "<<b<<" "<<endl;
 a=a*b;   //a=200(10*20)
 b=a/b;   //a= 10(200/20)
 a=a/b;   //a=20(200/10)
 cout<<"After swapping: "<<a<<" "<<b<<" "<<endl;
 return 0;
 } 

Output:

 Before swapping: 10  20
 After Swapping:  20  10 

Explanation:

Here, we have used multiplication ( * ) and division( / ) operator to swap the values of a & b. The logic is quite simple to understand from the code itself.

Let us now look at the second way of swapping.

  • Using + and -
int main()
 {
 int a=10,b=20;
 cout<<"Before swapping: "<<a<<" "<<b<<" "<<endl;
 a=a+b;   //a=30(10+20)
 b=a-b;   //a=10 (30-20)
 a=a-b;   //a=20(30-10)
 cout<<"After swapping: "<<a<<" "<<b<<" "<<endl;
 return 0;  {
 int a=10,b=20;
 cout<<"Before swapping: "<<a<<" "<<b<<" "<<endl;
 a=a+b;   //a=30(10+20)
 b=a-b;   //a=10 (30-20)
 a=a-b;   //a=20(30-10)
 cout<<"After swapping: "<<a<<" "<<b<<" "<<endl;
 return 0; 
}

Output:

 Before swapping: 10  20
 After Swapping:  20  10 

Explanation:

Here, we have used addition( + ) and subtraction( - ) operators to swap the values of a & b. The logic is quite simple to understand from the code itself.

More about swapping:

Swapping in numbers in any programming language is an easy concept of exchanging or interchanging values. We can also do this by taking input from the user and then interchange the values using simple operations. There are no hard and fast rules to swap numbers in C++. Earlier we used two methods where first method uses ( * ) &( / ) operators and second method uses ( + ) * ( - ) operators. It could have been also done in different ways, which provides a method for every beginner or an expert to swap numbers according to their level of understanding. The above examples are the simplest ways for a beginner in programming to understand how the swapping operation works in C++.

To be more practical, one needs to practice these swapping techniques in order to solve other problems where other logic can be easily implemented. But in general terms, it is recommended to use these techniques. It is easier to understand how the working of each line takes place. C++ makes it easier to understand because of its simple syntax.


Related Topics

Single level Inheritance

Inheritance is a fundamental element of C++’s Object-Oriented Programming (OOP). It allows a class (called the derived class) to inherit characteristics and attributes from another class (called the base class)....

5 minutes read.

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.

Timsort Implementation Using C++

Timsort Implementation Using C++ The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion...

3 minutes read.

Message Passing in C++

The act of sending and receiving information by an object is referred to as communication, and all communication between objects that takes place via message is known as message passing....

1 minute read.

Reverse function in C++

The function std::reverse() is included in the standard template library of C++. It takes in a beginning and ending iterator, reversing the order. To use the reverse statement, we need...

2 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

Division in C++

C++ Division Arithmetic Operation In C++ the arithmetic operator / is used for division. This operator takes two operands and returns the result of dividing the left operand by the right...

3 minutes read.

4-Dimensional Array in C/C++

A four-dimensional (4D) array is an array of three-dimensional (3D) arrays, or in other words we can say that a 4- dimensional array is an array of arrays of arrays...

3 minutes read.

C++ Output Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

4 minutes read.

Decltype type Specifier in C++

The primary use of C++ decltype is to inspect the declaration type of an entity in an expression. The auto keyword can declare a particular type of variable, whereas the...

4 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

Find the Size of Array in C/C++ without using sizeof() function

We know that arrays in C/C++ are the most essential data structures as they have the ability to hold the data in a continuous manner line where the address of...

3 minutes read.