The Wayback Machine - https://web.archive.org/web/20240906232348/https://www.geeksforgeeks.org/how-to-swap-two-numbers-using-pointers-in-cpp/
Open In App

How to Swap Two Numbers Using Pointers in C++?

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

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++, pointers are variables that store the memory address of another variable. Using pointers the value of variables can be changed directly as we have direct access to the address of the variables. Using this feature of pointers we will swap two numbers. Following is the algorithm we will follow to swap two numbers using pointers in C++:

Algorithm

  • Declare a function swap that takes two integer pointers x and y as parameters.
  • Use a temporary variable temp to store the value of x.
    • temp=*x;
  • Store the value of y in x by dereferncing the pointers.
    • *x=*y
  • Store the value of temp in y.
    • *y=temp;
  • Call the swap function by passing the address of x and y.

If you are not familiar with the concept of dereferencing, you can read the following article –> C++ Dereferencing

C++ Program to Swap Two Numbers using Pointers

The following program illustrates how we can swap two numbers using pointers in C++:

C++
// C++ Program to Swap Two Numbers using Pointers
#include <iostream>  
using namespace std;

// Function to swap two Numbers using pointers
void swap(int* x, int* y) {
    // Store the value pointed to by x in temp
    int temp = *x; 
    // Assign the value pointed by y to the location pointed to by x
    *x = *y;      
    // Assign the value stored in temp to the location pointed to by y
    *y = temp;      
}

int main() {
    // Initialize two numbers x and y
    int x = 5, y = 10;  
    // Print values before swapping
    cout << "Before swapping: x = " << x << ", y = " << y << endl;  

    // Call the swap function, passing the addresses of x and y
    swap(&x, &y);
    
    // Print values after swapping
    cout << "After swapping: x = " << x << ", y = " << y << endl;  
    return 0;  
}

Output
Before swapping: x = 5, y = 10
After swapping: x = 10, y = 5

Time Complexity: O(1)
Auxiliary Space: O(1)

Want to learn about other approaches to swap two numbers? Refer to the following articles:




Similar Reads

Difference between constant pointer, pointers to constant, and constant pointers to constants
In this article, we will discuss the differences between constant pointer, pointers to constant &amp; constant pointers to constants. Pointers are the variables that hold the address of some other variables, constants, or functions. There are several ways to qualify pointers using const. Pointers to constant.Constant pointers.Constant pointers to c
3 min read
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
C++ Program to compare two string using pointers
Given two strings, compare the strings using pointers Examples: Input: str1 = geeks, str2 = geeks Output: Both are equal Input: str1 = hello, str2 = hellu Output: Both are not equal As their length are same but characters are different The idea is to dereference given pointers, compare values and advance both of them. C/C++ Code // C++ Program to c
1 min read
Move all zeroes to end of array using Two-Pointers
Given an array of random numbers, Push all the zero’s of the given array to the end of the array. For example, if the given arrays is {1, 0, 2, 6, 0, 4}, it should be changed to {1, 2, 6, 4, 0, 0}. The order of all other elements should be the same.Examples: Input: arr[]={8, 9, 0, 1, 2, 0, 3} Output: arr[]={8, 9, 1, 2, 3, 0, 0} Explanation: Swap {0
6 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
C++ Program to Swap Two Numbers
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. 1. Swap Numbers Using a Temporary VariableWe 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
4 min read
C++ Program for Two Pointers Technique
Two pointers is really an easy and effective technique which is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X. Let’s see the naive solution. C/C++ Code // Naive solution to find if th
4 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 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
Computing Index Using Pointers Returned By STL Functions in C++
Many inbuilt functions in C++ return the pointers to the position in memory which gives an address of the desired number but has no relation with the actual index in a container of the computed value. For example, to find the maximum element in a code, we use std::max_element(), which returns the address in memory, not the index of the desired elem
3 min read
How to Sort an Array of Strings Using Pointers in C++?
In C++, sorting an array of strings using pointers is quite different from normal sorting because here the manipulation of pointers is done directly, and then according to which string is pointed by the pointer the sorting is done. The task is to sort a given array of strings using pointers. Example Input: strArray[] = {"Apple", "Orange", "Banana",
2 min read
How to Avoid Memory Leaks When Using a Vector of Pointers to Dynamically Allocated Objects in C++?
In C++, managing memory properly is very important to avoid memory leaks, especially when working with dynamically allocated objects. When using a std::vector of pointers to dynamically allocated objects, we need to ensure that all allocated memory is properly deallocated. In this article, we will learn different methods to avoid memory leaks in su
6 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
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
Features and Use of Pointers in C/C++
Pointers store the address of variables or a memory location. Syntax: datatype *var_name; Example: pointer "ptr" holds the address of an integer variable or holds the address of memory whose value(s) can be accessed as integer values through "ptr" int *ptr; Features of Pointers: Pointers save memory space.Execution time with pointers is faster beca
2 min read
Program to implement Separate Chaining in C++ STL without the use of pointers
Pre-requisite: Separate Chaining, STL in C++ This article implements the Separate Chaining in Hashing with help of STL in C++ without the use of pointers. Approach: Make an array of vectors to get a dynamic (resizable) array for every hash index rather than using a linked list to do the same. Now it becomes easier to work on the data-set without us
4 min read
How many levels of pointers can we have in C/C++
Prerequisite: Pointer in C and C++, Double Pointer (Pointer to Pointer) in CA pointer is used to point to a memory location of a variable. A pointer stores the address of a variable and the value of a variable can be accessed using dereferencing of the pointer. A pointer is generally initialized as: datatype *variable name; This above declaration i
7 min read
Why do we need reference variables if we have pointers
Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be de referenced with * operator to access the memory location it points to.References: A Reference can be called as a constant pointer that becomes de referenced implicitly. When we access the reference it means we are accessing the storage.Why do w
4 min read
Unusual behaviour with character pointers
In C++, cout shows different printing behaviour with character pointers/arrays unlike pointers/arrays of other data types. So this article will firstly explain how cout behaves differently with character pointers, and then the reason and the working mechanism behind it will be discussed. Example 1: C/C++ Code // C++ program to illustrate difference
5 min read
Creating array of pointers in C++
An array of pointers is an array of pointer variables. It is also known as pointer arrays. We will discuss how to create a 1D and 2D array of pointers dynamically. The word dynamic signifies that the memory is allocated during the runtime, and it allocates memory in Heap Section. In a Stack, memory is limited but is depending upon which language/OS
5 min read
C++ Modify Pointers
Prerequisite: Pointer in C++ Pointers are an essential part of the C++ language. It allows us to store the memory address of a variable. One thing to note here is that if we change the value that a pointer is pointing to, then the value of the original variable also changes. Now, let's check the approach we are going to use. Approach: In the below
2 min read
C++ Vector of Pointers
Prerequisites Pointers in C++Vectors in C++ Vector of pointers are vectors that can hold multiple pointers. Each pointer within a vector of pointers points to an address storing a value. We can use the vector of pointers to manage values that are not stored in continuous memory. How to Create Vector of Pointers in C++? Similar to any other vector d
6 min read
Pointers in Containers in C++ STL
Prerequisites: Pointers in C++Container in STL There are different containers in C++ having their own features where if are adding extra functionality of pointer it will contribute in a different way. Although not all of the containers are useful in this context so let's see a few of the containers which can be helpful. There are 5 containers that
5 min read
Passing Pointers to Functions In C++
Prerequisites: Pointers in C++Functions in C++ Passing Pointers to functions means declaring the function parameter as a pointer, at the function calling passing the address of the variable and that address will be stored by a parameter that is declared as a pointer. To change the value of any variable in the function we have to pass the address of
4 min read
Lambda Expressions vs Function Pointers
Function Pointer: A function pointer, or a subroutine pointer, or a procedure pointer, is a pointer that points to a function. In simple words, it is a pointer to the location inside the text section. It stores the address of a function and is used for passing a behavior as a parameter to another function. For instance, if someone wants to sort a c
7 min read
What are Wild Pointers? How can we avoid?
Uninitialized pointers are known as wild pointers because they point to some arbitrary memory location and may cause a program to crash or behave unexpectedly. Example of Wild PointersIn the below code, p is a wild pointer. C/C++ Code // C program that demonstrated wild pointers int main() { /* wild pointer */ int* p; /* Some unknown memory locatio
2 min read
Declare a C/C++ function returning pointer to array of integer pointers
Declare "a function with argument of int* which returns pointer to an array of 4 integer pointers". At the first glance it may look complex, we can declare the required function with a series of decomposed statements. 1. We need, a function with argument int *, function(int *) 2. a function with argument int *, returning pointer to (*function(int *
2 min read
Pointers vs References in C++
Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and pointers are very similar as both are used to hav
5 min read
Practice Tags :