Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
C++ Program To Add Two Binary Strings
Next article icon

C++ Program to Swap Two Numbers

Last Updated : 02 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.


Next Article
C++ Program To Add Two Binary Strings
author
ayonssp
Improve
Article Tags :
  • C++ Programs
  • C++
  • C Basic Programs
Practice Tags :
  • CPP

Similar Reads

  • 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=1
    3 min read
  • C++ Program to Rotate bits of a number
    Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end. In left rotation, the bits that fall off at left end are put back at right end. In right rotation, the bits that fall off at right end are put ba
    3 min read
  • TCS Coding Practice Question | Swap two Numbers
    Given two numbers, the task is to swap the two numbers using Command Line Arguments. Examples: Input: n1 = 10, n2 = 20 Output: 20 10 Input: n1 = 100, n2 = 101 Output: 101 100 Approach: Since the numbers are entered as Command line Arguments, there is no need for a dedicated input lineExtract the inp
    3 min read
  • C++ Program To Add Two Binary Strings
    Given two binary strings, return their sum (also a binary string).Example: Input: a = "11", b = "1" Output: "100" We strongly recommend you to minimize your browser and try this yourself first The idea is to start from the last characters of two strings and compute the digit sum one by one. If the s
    3 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 ta
    6 min read
  • C++ Program to Implement Half Subtractor
    A Half Subtractor is a digital logic circuit that is used to subtract two single-bit binary numbers. In this article, we will learn how to implement the half subtractor logic in C++. What is a Half Subtractor?As told earlier, half subtractor is a digital logic circuit that makes the use of logical g
    2 min read
  • C++ Program For String to Double Conversion
    There are situations, where we need to convert textual data into numerical values for various calculations. In this article, we will learn how to convert strings to double in C++. Methods to Convert String to Double We can convert String to Double in C++ using the following methods: Using stod() Fun
    3 min read
  • C++ Program For Insertion Sort
    Insertion sort is a simple sorting algorithm that works by dividing the array into two parts, sorted and unsorted part. In each iteration, the first element from the unsorted subarray is taken and it is placed at its correct position in the sorted array. In this article, we will learn to write a C++
    3 min read
  • C++ Program For Selection Sort
    The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. The subarray which is already sorted. Remaining subarray which is unsorted.
    4 min read
  • C++ Program To Subtract Two Numbers Represented As Linked Lists
    Given two linked lists that represent two large positive numbers. Subtract the smaller number from the larger one and return the difference as a linked list. Note that the input lists may be in any order, but we always need to subtract smaller from the larger ones.It may be assumed that there are no
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences