• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

[3 Ways] C/C++ Program to Swap Two Numbers Without Using Temporary Variable

Aniruddha Chaudhari/19038/2
C / C++Code

Conventionally in order to swap two numbers, we use the third variable temp. Swapping two variables is quite comfortable using a temporary variable.

What if the interviewer asks you to swap the numbers without any extra space. Swapping two numbers without using a temporary variable makes the thing interesting.

How to Swap two numbers without using temporary variable?

If you want to swap any two numbers, there are ways to swap the integer or float values by using some sort of arithmetic and bit manipulation operation.

There are three ways for swapping numbers using…

It looks messy at first, but when you look into these, it’s a just simple pattern to remember.

1. Swapping Using Addition and Subtraction operation

x = x + y
y = x - y
x = x - y

Addition and subtraction are arithmetic operations. This method can apply for swapping integer as well as floating type values.

#include<stdio.h>;
int main()
{
  // intialise two variables
  int x = 25, y = 17;
  // Arithmatic Code to swap 'x' and 'y'
  x = x + y;  // after addition x with contain 42
  y = x - y;  // y will contanis 25
  x = x - y;  // x becomes 17
  
  printf("After Swapping two values: x = %d, y = %d", x, y);
  
  return 0;
}

Output:

After Swapping two values: x = 17, y = 25

This method is easy to understand as like arithmetic addition and subtraction methods.

2. Swapping Using Multiplication and Division operation

x = x * y
y = x / y
x = x / y
#include<stdio.h>;
int main()
{
  // intialise two variables
  int x = 25, y = 17;
  // Arithmatic multiplicatio and division Code to swap 'x' and 'y'
  x = x * y;  // after addition x with contain 42
  y = x / y;  // y will contanis 25
  x = x / y;  // x becomes 17
  
  printf("After Swapping two numbers: x = %d, y = %d", x, y);
  
  return 0;
}

It is similar to the first method. The only difference is that it uses multiplication operation instead of addition and division operation instead of subtraction.

Output:

After Swapping two numbers: x = 17, y = 25

Note: This method will not work in case any of the numbers (x or y) are zero.

3. Swapping Two Numbers Using XOR operation

x = x ^ y
y = x ^ y
x = x ^ y

Note: If you are swapping two values using the XOR bit operation, it works for integers only.

C Code:

#include<stdio.h>;
int main()
{
  // intialise two variables
  int x = 25, y = 17;
  // XOR Bit operation Code to swap 'x' and 'y'
  x = x ^ y;  // after addition x with contain 42
  y = x ^ y;  // y will contanis 25
  x = x ^ y;  // x becomes 17
  
  printf("After Swapping two values: x = %d, y = %d", x, y);
  
  return 0;
}

Output:

After Swapping two values: x = 17, y = 25

C++ Code:

Write a C++ program to swap two numbers without using extra space.

#include <iostream>
using namespace std;
 
int main()
{
    int a= 13;
    int b=5;

    cout<< a << "  "<<b<<endl; 

    a = a^b;
    b = a^b;
    a = a^b;

    cout<<a<<"  "<<b; 

    return 0;
}

This code snippet is shared by Om Tayade.

The XOR bit operation method is easy to remember as it uses a single operation.

I have described all these methods by writing code in C and C++. You can use all the above three methods to write a program in any language to swap two numbers without using a temporary variable.

If you are a Python developer, you don’t need to do this as well. You can write a Python program to swap two variables without using a third variable by a just single line of code.

Do you know any other method to swap two variables? You can write in the comment section below. I would like to mention that in this post as well.

cpp
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Anouar EL MOKHTARI
    October 27, 2021 at 3:02 pm

    In the multiplication method, it should be mentioned that x and y should not be equal to zero.

    • Reply
      Aniruddha Chaudhari
      October 29, 2021 at 8:15 am

      Good catch. Added note in the tutorial. Thanks!

Leave a Reply Cancel reply

C Programming

  1. C- Introduction
  2. C- Compile & Execute Program
  3. C- Data Types
  4. C- if-else statement
  5. C- While, do-while, for loop
  6. C- Array
  7. C- Function (Types/Call)
  8. C- strlen() vs sizeof()
  9. C- Nested Switch Statement
  10. C- Recursion
  11. C- Dynamic Programming
  12. C- Storage Classes
  13. C- Creating Header File
  14. C- Null Pointer
  15. C- Stack and Queue
  16. C- Implement Stack using Array
  17. C- Implement Linked List in C
  18. C- File Handling
  19. C- Makefile Tutorial

Object Oriented Concepts in C++

  • C++: C vs OOPs Language
  • C++: Introduction to OOPs Concepts
  • C++: Inheritance

Sorting Algorithms

  • Different Types of Sorting Algo
  • Selection Sort
  • Bubble Sort
  • Quick Sort

Programming for Practice

  1. Online C/C++ Compiler

String Handling:

  1. Remove White Spaces from String
  2. Implement strstr Function in C
  3. Convert String to Int – atoi()
  4. Check if String is Palindrome
  5. Check if Two Strings are Anagram
  6. Split String in using strtok_r()
  7. Undefined reference to strrev

Array:

  1. Check if Array is Sorted

Bit Manipulation:

  1. Count Number of 1’s in Binary

Linked List:

  1. Reverse a Linked List Elements

Number System:

  1. Program to Find 2’s Complement
  2. Convert Decimal to Binary in C

Tricky Questions:

  1. Add Two Numbers without Operator
  2. Find Next Greater Number
  3. Swap values without temp variable
  4. Print 1 to 100 without Loop

Interview Coding Questions

  • 50+ Interview Coding Questions

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard