Flag This Hub

Swapping two variables without using third variable program.

By


One of my friends (visitor) asked me in comment section “how to swap two variables without using temp variable” and I thought of sharing that answer with all my friends (visitors). For the first I am also going to provide full code in Java and C# language and my future articles will have codes in Java and C# along with C language. Along with regular logic of swapping variable I will show you how to do that without using third variable in C, Java and C# (C-Sharp).

C program to swap two numbers using third (temp) variable

#include<stdio.h>
#include<conio.h>

void main()
{
	int a=100, b=30, temp;
	clrscr();

	temp = a;
	a = b;
	b = temp;

	printf("Swapping using third (temp) variable.\n\n");
	printf("Value of a=%d and b=%d.", a,b);
	getch();
}
Program output of swap two numbers using third variable in C language.
See all 4 photos
Program output of swap two numbers using third variable in C language.

Explanation

This is an absolute beginner section and if you think you are good in C language then you can skip this section. Above is a simple c program to swap two numbers using temp variable. You must be thinking why I am explaining such an easy program. Actually I thought there is some important point which most of you are familiar with but still I feel for beginners it’s important.

Let’s start then, we are declaring three integer variable in line no 6 and I found that many people think variable name “temp” in different way. They think that “temp” is a magical thing rather than an integer variable. Let me tell you friends that is only name of the variable, we name variable according to its use in program. So don’t get confuse with such names. You just need to check its data type and all confusion will be clear.

Let me also tell you why I named that variable as “temp”. If you notice code block (line no 9-11), you will come to know that in line no. 9 we are assigning value of “a” to “temp” (i.e. temp=100, a =100 & b=30) variable and in very next line (line no. 10) we are assigning value of “b” to “a” (i.e. a=30, b =30 & temp=100) variable and in last line (line no. 11) we assigning value of “temp” to “b” variable (i.e. b=100, temp =100 & a=30). In this entire program “temp” variable is used to hold value of “a” so that we can use it value later (like in line no. 11). Because I used it to store value temporarily so I named it “temp”.

Apple products

USB Sync and Charging Cable Compatible with Apple iPhone (White)
Amazon Price: $0.01
List Price: $24.99
Apple MacBook Pro MD313LL/A 13.3-Inch Laptop (NEWEST VERSION)
Amazon Price: $1,099.99
List Price: $1,199.00
Apple MacBook Pro MD311LL/A 17-Inch Laptop (NEWEST VERSION)
Amazon Price: $2,249.00
List Price: $2,499.00
Apple TV MD199LL/A [NEWEST VERSION]
Amazon Price: $99.00
Earphone Headset With Remote Mic for Apple iPhone 4S 4 4G 3GS 3G
Amazon Price: $0.01
List Price: $29.99
Apple iPod touch 8 GB 4th Generation (White)
Amazon Price: $174.99
List Price: $199.00

C language books

C Programming Language (2nd Edition)
Amazon Price: $35.64
List Price: $67.00
C (Vintage)
Amazon Price: $1.03
List Price: $15.00
Programming in C (3rd Edition)
Amazon Price: $24.00
List Price: $49.99
C Primer Plus (5th Edition)
Amazon Price: $30.63
List Price: $54.99
Absolute Beginner's Guide to C (2nd Edition)
Amazon Price: $19.00
List Price: $39.99
C Programming: A Modern Approach, 2nd Edition
Amazon Price: $66.23

C program to swap two numbers without using third variable

#include<stdio.h>
#include<conio.h>

void main()
{
	int a=100, b=30;
	clrscr();

	a = a+b;
	b = a-b;
	a = a-b;

	printf("Swapping without using third variable (using + and -).\n\n");
	printf("Value of a=%d and b=%d.", a,b);
	getch();
}
Program output of "swap two numbers without using third variable in C language"
Program output of "swap two numbers without using third variable in C language"

In above program to swap two numbers we are not using any third or temp variable like we did in our first program. Here we are only using two arithmetic operators (+ & -) to swap values between “x” and “y”. Let’s see how it works,

	a=100;
	b=30;

	a = a+b;
	a = 100 + 30; 
	a = 130;

	b = a-b;
	b = 130 - 30; 
	b = 100; // b has value of a.

	a = a-b;
	a = 130 - 100;
	a = 30; // a has b's value.

I don’t think after that illustration you guys need any explanation on logical part of the program.

You would be happy when you will come to know that there is some other methods for swapping two numbers. Let me quickly show you the code.

Method 2 : Swap two numbers without third variable in C

#include<stdio.h>
#include<conio.h>

void main()
{
	int a=100, b=30;
	clrscr();

	a = a*b;
	b = a/b;
	a = a/b;

	printf("Swapping without using third variable (using * and /).\n\n");
	printf("Value of a=%d and b=%d.", a,b);
	getch();
}
Program output of "swap two numbers without using third variable in C language"
Program output of "swap two numbers without using third variable in C language"

Method 3 : Swap two numbers without third variable in C

#include<stdio.h>
#include<conio.h>

void main()
{
	int a=2, b=4;
	clrscr();

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

	printf("Swapping without using third variable (using ^).\n\n");
	printf("Value of a=%d and b=%d.", a,b);
	getch();
}
Program output of "swap two numbers without using third variable in C language"
Program output of "swap two numbers without using third variable in C language"

I think Method 2 is easy enough and don’t need any explanation. But Method 3 requires some explanation, so I will explain here Method 3 and if you find difficulty with Method 2 you can always ask me.

In Method 3 I am using bitwise XOR operator for swapping variable’s value. I hope all you guys are aware of bitwise binary operator like NOT, AND, OR etc. Because we are going to use that here, don’t worry guys I’ll try to “Keep It Simple and Stupid”. Just to refresh your memory about XOR below I provided truth table of XOR operator. Basically we are going see how XOR helps us to swap variable.

For illustration purpose I am taking small values in variable “a” and “b”.

XOR Truth Table

A
B
Result (A XOR B)
0
0
0
0
1
1
1
0
1
1
1
0

Explanation:

a=2, b=4;


a=a^b;

0010 (equals to 2)

0100 (equals to 4)

------ (After XOR)

0110 (equals to 6)

a=6;


b=a^b;

0110 (equals to 6)

0100 (equals to 4)

------ (After XOR)

0010 (equals to 2)

b=2;


a=a^b;

0110 (equals to 6)

0010 (equals to 2)

------ (After XOR)

0100 (equals to 4)

a=4;

When we do XOR between “a & b” (i.e. a^b or 2^4) we get “6” (i.e. a=6, check the first code block). In the next C code block we are doing the same XOR between “a & b” but here value of “a” is “6”, so (i.e. a^b or 6^4) we get “2” (i.e. b=2). Similarly when we do XOR between “a & b” in the last block (i.e. a^b or 6^2) we get “4” (i.e. a=4). This is how we can swap variable’s value using XOR operation. I hope it is clear for you.

Method 1 : Swapping of two numbers in C#

using System;

namespace SwapVariables
{
    class Method1
    {
        static void Main(string[] args)
        {
            int a = 100, b = 30;

            a = a + b;
            b = a - b;
            a = a - b;

            Console.WriteLine("Swapping without using third variable (using + and -).\n\n");
            Console.WriteLine("Value of a = {0} and b= {1}.", a, b);
            Console.ReadKey();
        }
    }
}

Method 2 : Swapping of two numbers in C#

using System;

namespace SwapVariables
{
    class Method2
    {
        static void Main(string[] args)
        {
            int a = 100, b = 30;

            a = a * b;
            b = a / b;
            a = a / b;

            Console.WriteLine("Swapping without using third variable (using * and /).\n\n");
            Console.WriteLine("Value of a = {0} and b= {1}.", a, b);
            Console.ReadKey();
        }
    }
}

Method 3 : Swapping of two numbers in C#

using System;

namespace SwapVariables
{
    class Method3
    {
        static void Main2(string[] args)
        {
            int a = 100, b = 30;

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

            Console.WriteLine("Swapping without using third variable (using ^).\n");
            Console.WriteLine("Value of a = {0} and b= {1}.", a, b);
            Console.ReadKey();
        }
    }
}

Method 1 : Swapping of two numbers in Java

public class Method1 {
	public static void main(String[] args) {

		int a = 100, b = 30;

		a = a + b;
		b = a - b;
		a = a - b;

		System.out.println("Swapping without using third variable (using + and -).\n");
		System.out.println("Value of a = " + a + " and b= " + b);
	}
}

Method 2 : Swapping of two numbers in Java

public class Method2 {
	public static void main(String[] args) {

		int a = 100, b = 30;

		a = a * b;
		b = a / b;
		a = a / b;

		System.out.println("Swapping without using third variable (using * and /).\n");
		System.out.println("Value of a = " + a + " and b= " + b);
	}
}

Method 3 : Swapping of two numbers in Java

public class Method3 {
	public static void main(String[] args) {

		int a = 100, b = 30;

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

		System.out.println("Swapping without using third variable (using ^).\n");
		System.out.println("Value of a = " + a + " and b= " + b);
	}
}

Share your opinion with me

Did this article help you to understand topic (How to swap two numbers without using third (temp) variable.)?

  • Yes, its well written and well explained.
  • No, I need more clarification on topic. (Please suggest)
  • This tutorial need improvements (Please suggest).
See results without voting

Comments

raj 7 months ago

it is more useful

utkarsh 6 months ago

superb boss............excellent thanxxx for helping me out.

nikhil so. 6 months ago

a re same tech. use other also r u na

aruna 6 months ago

its so wonderful.

ersran9 5 months ago

just use std::swap in c++?

asha 5 months ago

thanks

saran 4 months ago

swap the variable without using temp variable and arithmetic operator

k k j 4 months ago

nice it saves memories!!

Ganesh 3 months ago

Its very useful but little bit of changes need

chethan 3 months ago

it is really helping a lot

renu 2 months ago

super

Sunney 2 months ago

Do you have any strategy for swapping two arrays without temp array?????????

Anon 2 months ago

In the 'C' examples, you probably ought to use '+=' and '-=', rather than '='.

Not sure if this will work in cases of overflow...And too lazy to check.

Ananya Banerjee 2 months ago

It help me a lot.....!!!!

chandan 7 weeks ago

thanx bhai , nice man, superb......

Submit a Comment
Members and Guests

Sign in or sign up and post using a hubpages account.



    Like this Hub?
    Please wait working