ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How to Swap Two Numbers in C, Java and C#

Updated on July 9, 2018
rajkishor09 profile image

Raj is an ardent coder who loves exploring new technology. He is an IT pro with over a decade of experience in C#, Angular, React, and Vue.

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.
Program output of swap two numbers using third variable in C language. | Source

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”.

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" | Source

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" | Source

Swapping of two numbers in C using XOR (^) operator without third variable

#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" | Source

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.

Simple method to swap 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();
        }
    }
}

Simple but different approach to swap 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();
        }
    }
}

Swapping of two numbers in C# using XOR (^) operator

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();
        }
    }
}

Simple method to swap 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);
	}
}

Simple but different approach to swap 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);
	}
}

Swapping of two numbers in Java using XOR (^) operator

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.)?

See results

© 2011 RAJKISHOR SAHU

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)