The Wayback Machine - https://web.archive.org/web/20240906185858/https://www.geeksforgeeks.org/cpp-program-to-swap-two-numbers/
Open In App

C++ Program to Swap Two Numbers

Last Updated : 02 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Swapping numbers is the process of interchanging their values. In this article, we will learn algorithms and code to swap two numbers in the C++ programming language.

swap two numbers in c++

1. Swap Numbers Using a Temporary Variable

We can swap the values of the given two numbers by using another variable to temporarily store the value as we swap the variables’ data. The below algorithm shows how to use the temporary variable to swap values.

Algorithm

  1. Assign a to a temp variable: temp = a
  2. Assign b to a: a = b
  3. Assign temp to b: b = temp

C++ Program to Swap Two Numbers using a Temporary Variable.

C++
// C++ program to swap two
// numbers using 3rd variable
#include <bits/stdc++.h>
using namespace std;

// Driver code
int main()
{
    int a = 2, b = 3;

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

    // temporary variable
    int temp;

    // appying swapping algorithm
    temp = a;
    a = b;
    b = temp;
    cout << "After swapping a = " << a << " , b = " << b
         << endl;

    return 0;
}

Output
Before swapping a = 2 , b = 3
After swapping a = 3 , b = 2

Complexity Analysis

  • Time Complexity: O(1) as only constant operations are done.
  • Space Complexity: O(1) as no extra space has been used.

2. Swap Numbers Without Using a Temporary Variable

We can also swap numbers without using the temporary variable. Unlike the previous method, we use some mathematical operations to swap the values.

Algorithm

  1. Assign to b the sum of a and b i.e. b = a + b.
  2. Assign to a difference of b and a i.e. a = b – a.
  3. Assign to b the difference of b and a i.e. b = b – a.

C++ Program to Swap Two Numbers Without Using a Temporary Variable.

C++
// C++ program to swap two
// numbers without using 3rd
// variable
#include <bits/stdc++.h>
using namespace std;

// Driver code
int main()
{
    int a = 2, b = 3;

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

    // applying algorithm
    b = a + b;
    a = b - a;
    b = b - a;

    cout << "After swapping a = " << a << " , b = " << b
         << endl;
    return 0;
}

Output
Before swapping a = 2 , b = 3
After swapping a = 3 , b = 2

Complexity Analysis

  • Time Complexity: O(1), as only constant time operations are done.
  • Space Complexity: O(1), as no extra space has been used.

3. Swap Two Numbers Using Inbuilt Function

C++ Standard Template Library (STL) provides an inbuilt swap() function to swap two numbers.

Syntax of swap()

swap(a, b);

where a and b are the two numbers.

C++ Program to Swap Two Numbers Using the Inbuilt swap() Function.

C++
// C++ program to swap two
// numbers using swap()
// function
#include <bits/stdc++.h>
using namespace std;

// Driver code
int main()
{
    int a = 5, b = 10;

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

    // Built-in swap function
    swap(a, b);

    cout << "After swapping a = " << a << " , b = " << b
         << endl;
    return 0;
}

Output
Before swapping a = 5 , b = 10
After swapping a = 10 , b = 5

Complexity Analysis

  • Time Complexity: O(1) as only constant operations are done.
  • Space Complexity: O(1) as no extra space has been used.

Refer to the complete article How to swap two numbers without using a temporary variable? for more methods to swap two numbers.



Similar Reads

Difference between std::swap and std::vector::swap
The std::swap is a general function used to exchange the given values whereas the std::vector::swap is a specialized function that can swap all the contents of two different vector containers.Below are some major key differences between std::swap and std::vector::swap, std::swapstd::vector::swapThe std::swap() is a built-in function in C++ STL whic
3 min read
Swap Two Numbers using Function in C++
Swapping numbers means exchanging the values of the two numbers with each other. For Example, Before Swapping:a = 10, b = 22;After swapping:a = 22, b = 10In this article, we will write a program to swap two numbers using a function in C++. How to Swap Two Numbers Using Function in C++?We will pass the address or reference of the two variables that
3 min read
Swap Two Numbers Without Third Variable in C++
In C++, swapping two numbers means we need to exchange the value of two numbers. In this article, we will learn how to swap two numbers without using the third variable in C++. Example Input: a=10b=20Output:After swapping:a=20b=10Swap Two Numbers Without Using a Third VariableIn C++ we can swap two numbers without using a temporary variable by usin
2 min read
How to Swap Two Numbers Using Pointers in C++?
Swapping the values of two numbers is a very common operation in programming, which is often used to understand the basics of variables, pointers, and function calls. In this article, we will learn how to swap two numbers using pointers in C++. Example Input:int x=10;int y=20;Output:int x=20;int y=10;Swap Two Numbers Using Pointers in C++In C++, po
3 min read
C++ Program to swap two members using Friend Function
Pre-requisite: Friend FunctionCASE 1: Given two numbers a &amp; b, swap these two numbers using the friend function of C++. Examples: Input : a = 5, b = 9 Output : a = 9, b = 5 Input : a = 4, b = 6 Output : a= 6, b = 4 Approach: Create a class Swap, declare three variables in it, i.e., a, b, and temp and create a constructor for inputs. Declare a f
3 min read
Swap Two Variables in One Line
We have discussed different approaches to swap two integers without the temporary variable. How to swap into a single line without using the library function?1) Python: In Python, there is a simple and syntactically neat construct to swap variables, we just need to write "x, y = y, x".2) C/C++: Below is one generally provided classical solution: //
4 min read
Swap Two Variables Using XOR
In C++, variables are containers that store data. Sometimes, we may need to swap the values of two variables. The traditional method involves using a third variable as a temporary storage to facilitate the swap. In this article, we will learn how to swap two variables using the XOR technique. Example: Input: a = 5; b = 10; Output: a = 10; b = 5;Swa
2 min read
How to Swap Two Strings Without Using Third String in C++?
In C++, a string is a sequence of characters. Swapping two strings typically involves using a third string as temporary storage. However, it’s possible to swap two strings without using a third string. In this article, we will learn how to do this in C++. Example Input: str1 = "Hello" str2 = "world" Output: str1 = "world" str2 = "Hello"Swapping Str
2 min read
How to quickly swap two arrays of same size in C++?
Given two arrays a[] and b[] of same size, we need to swap their contents. Example : Input: a[] = {1, 2, 3, 4} b[] = {5, 6, 7, 8}Output: a[] = {5, 6, 7, 8}b[] = {1, 2, 3, 4} A simple solution is to iterate over elements of both arrays and swap them one by one. A quick solution is to use std::swap(). It can directly swap arrays if they are of same s
2 min read
C++ Program to Swap characters in a String
Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time. Your task is to find the final String after B swaps. Exam
6 min read
C++ Program for Block swap algorithm for array rotation
Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. Rotation of the above array by 2 will make array Algorithm : Initialize A = arr[0..d-1] and B = arr[d..n-1] 1) Do following until size of A is equal to size of B a) If A is shorter, divide B into Bl and Br such that Br is of same length as A. Swap A and Br to change ABl
4 min read
deque::at() and deque::swap() in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::at()at() function is us
4 min read
vector::at() and vector::swap() in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::at() at() function is used reference the element present at the position given as the parameter to the function. Syntax: vectorname.at(position) Parameter
4 min read
array::fill() and array::swap() in C++ STL
Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::fill() This function is used to set a common value for all the elements of the array container. Syntax : arrayname.fill(value) Parameters : The value to be
3 min read
forward_list::swap() in C++ STL
Forward list in STL implements singly linked list. Introduced from C++11, forward lists are useful than other containers for insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from the list by the fact that forward list keeps track of the location of only next element while lis
2 min read
queue::swap() in C++ STL
Queue is also an abstract data type or a linear data structure, which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). In a FIFO data structure, the first element added to the queue will be the first one to be removed. queue::swap() swap() function is used to exchange the contents of two queu
2 min read
set::swap() in C++ STL
Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. set::swap() This function is used to exchange the contents of two sets
2 min read
priority_queue::swap() in C++ STL
Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the smallest element at the top by simply passing an extr
3 min read
multiset::swap() in C++ STL
Multisets are a type of associative containers similar to set, with an exception that multiple elements can have same values. multiset::swap() This function is used to exchange the contents of two multisets but the sets must be of same type, although sizes may differ. Syntax : multisetname1.swap(multisetname2) Parameters : The name of the multiset
3 min read
multimap::swap() in C++ STL
multimap::swap() is used to swap the contents of one multimap with another multimap of same type and size. Syntax:- multimap1.swap(multimap2) Parameters : The name of the multimap with which the contents have to be swapped. Result : All the elements of the 2 multimap are swapped. Examples: Input: multimap1 = { ('a',1), ('b',2), ('c',3) multimap2 =
2 min read
map::at() and map::swap() in C++ STL
Maps are the container in STL which is used to store the elements in the form of key-value pair. Internally, the elements in a map are always sorted by its key. Maps are mainly implemented as binary search trees. map::at() at() function is used to return the reference to the element associated with the key k. Syntax: map1.at(k) Parameters: k is the
3 min read
forward_list::swap() in C++ STL
The forward_list::swap() is a built-in function in CPP STL which exchanges the contents of the first given forward_list with another forward_list. Syntax: swap(forward_list first, forward_list second) or forward_list1.swap(forward_list second) Parameters: The function accepts two parameters which are specified as below: first - The first forward_li
3 min read
multimap swap() function in C++ STL
The multimap::swap() is a built-in function in C++ STL which swaps two multimap container. The contents of multimap1 are in multimap2 and contents of multimap2 are in multimap1 after swap() function is called. Syntax: multimap1_name.swap(multimap2_name) Parameters: This function accepts one parameter which is to be swapped with the multimap1_name,
2 min read
unordered_set swap() function in C++ STL
The unordered_set::swap() method is a builtin function in C++ STL which is used to exchange values of two unordered_set containers. It swaps the element of two unordered_set containers. The sizes may differ but it swaps elements and changes the order of elements also.Syntax: unordered_set_firstname.swap(unordered_set_secondname) Parameter: The func
2 min read
unordered_multimap swap() function in C++ STL
The unordered_multimap::swap() is a built-in function in C++ STL which swaps the contents of two unordered_multimap containers. The sizes can differ of both the containers. Syntax: unordered_multimap_name1.swap(unordered_multimap_name2) Parameters: The function accepts a single mandatory parameter unordered_multimap_name2 which specifies the unorde
3 min read
unordered_set swap() in C++ STL
The swap() method of “unordered_set” swaps the contents of two containers. It is public member function. This function: Exchanges the content of the container by the content of variable, which is another unordered_set object containing elements of the same type but the sizes may differ. After the call to this member function, the elements in this c
3 min read
unordered_multiset swap() function in C++ STL
The unordered_multiset::swap() is a built-in function in C++ STL which swaps the contents of two unordered_multiset containers. Note: Both of the containers should have the same type of elements. Sizes of the containers may differ. Syntax: unordered_multiset1.swap(unordered_multiset2); Parameters: The function accepts only one compulsory parameter
3 min read
unordered_multiset swap() in C++ STL
The swap() method of “unordered_multiset” swaps the contents of two containers. It is public member function. This function: Exchanges the content of the container by the content of variable, which is another unordered_multiset object containing elements of the same type but the sizes may differ. After the call to this member function, the elements
3 min read
valarray swap() function in c++
The swap() function is defined in valarray header file. This function is used to swap the content of one valarray with another valarray. Syntax: void swap( valarray&amp; valarray2 ); Parameter: This method accepts a parameter valarray2 which represents the another valarray with which we have to swap the old one. Returns: This function doesn't retur
2 min read
unordered_map swap in C++ STL
The std::unordered_map::swap() is a built in function in C++ STL which swaps the elements of a container to an other container. After the call of this function elements of the caller unordered_map will be elements of called unordered_map while elements of called unordered_map will be elements of caller unordered_map. Internally swapping of elements
4 min read
Practice Tags :