×

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

Delete Operator in C++

Overview We can reserve allocation for a variable or an array at runtime in C++. Dynamic memory allocation is the term for this. After utilising a variable in C++, we must...

4 minutes read.

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

C++ vardiac() function

In the C++ programming language, the flexibility feature is provided by the variadic function. To understand more about flexibility, let's see the following syntax. Syntax: If we have to add two numbers,...

3 minutes read.

Type conversion in C++

Type conversion is the process of changing the type of variables in a program. The ultimate goal of type conversions is to allow variables of a single data type operate with...

7 minutes read.

C++ this pointer

'this' is a pointer that points to the object for which this function was called. The 'this' pointer holds the memory address of the current object. The 'this' pointer is implicitly passed to...

2 minutes read.

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 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.

C++ Goto

In this article, we will discuss the C++ goto statement with its syntax, use, key features, key points, pseudo code, and examples. What is the goto statement in C++? In C++, the...

4 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.

Multilevel Inheritance

C++ Multilevel Inheritance Multilevel inheritance is such an inheritance in which a derived class is created from another derived class. C++ Multilevel Inheritance Example In this example, a base class Student is inherited in...

2 minutes read.

C++ Writing to file

In file handling, write() function is used to write data into the file. The write() uses ofstream or fstream library to write into the file. Syntax file-stream-class   file-stream-object;   file-stream-object.write((char *)&var , sizeof (var)); The write() takes two arguments. The first argument is the address of variable var...

2 minutes read.

4 Pillars of OOPs

OOPs OOPS means Object Oriented Programming System Structure. Object oriented Programming is defined as an approach that provides a way of modularizing programs by creating partitioned memory area for both data...

11 minutes read.

How to Reverse a String in C++ using Do-While Loop

Strings In C++, a string is an object that represents a group (or sequence) of various characters. Strings are part of the standard string class in C++ (std::string). The characters of...

4 minutes read.

Features of OOPS in C++

What is OOPs? The main reason programmers prefer C ++ language over C is because of the support of object-oriented programing in C++. As the name suggests, object-oriented programming or OOPs...

3 minutes read.

C++ Friend function

A friend function has the right to access all private and protected members of a class although it is defined outside that class' scope. Syntax class className{     ......     friend retyrn_type function_Name(argument);     .......   }   return_type function_Name(argument){     ......   } C++ friend function Example #include <iostream>   using namespace std;   class Length   {       private:           int meter;       public:           Length(): meter(5) { }           friend int addMethod(Length); //friend function declaration   };   int addMethod(Length l) // friend function definition   {       l.meter += 10; //accessing private data from non-member function       return l.meter;   }   int main()   {       Length L;       int totallength;       totallength=addMethod(L);       cout<<"Length: "<< totallength;       return 0;   } Output: Length: 15   C++ friend function...

1 minute read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

RTTI (Run-Time Type Information) in C++

In C++, RTTI or Run-Time Type Information reveals information about the data type of an object at runtime and only works with classes that have at least one virtual function....

3 minutes read.

Array of sets in C++

Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. A collection of data objects stored in a continuous way is...

6 minutes read.