Swap two numbers without using third variable

Swap two numbers without using third variable in c

#include<stdio.h>
#include<conio.h>
void main()
{
	int a=100,b=200;
	printf("Before swap a=%d and b=%d \n",a,b);
	a=a+b;
	b=a-b;
	a=a-b;
	printf("After swap a=%d and b=%d \n",a,b);
	getch();
}

Output

Before swap a=100 and b=200
After swap a=200 and b=100

Swap two numbers without using third variable in c++

#include<iostream>
#include<conio.h>
using namespace std;
class SwapTwoNumbers
{
public:
	void Swap()
	{
	int a=300,b=400;
	cout<<"Before swap a="<<a<<" and b="<<b<<endl;
	a=a+b;
	b=a-b;
	a=a-b;
	cout<<"After swap a="<<a<<" and b="<<b;
	}
};
void main()
{
	SwapTwoNumbers stn;
	stn.Swap();
	getch();
}

Output

Before swap a=300 and b=400
After swap a=400 and b=300

Swap two numbers without using third variable in c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SwapTwoNumbersProject
{
    class SwapTwoNumbers
    {
        public void Swap()
        {
            int a = 12, b = 56;
            Console.WriteLine("Before swap a=" + a.ToString() + " and b=" + b.ToString());
            a = a + b;
            b = a - b;
            a = a - b;
            Console.WriteLine("After swap a=" + a.ToString() + " and b=" + b.ToString());
        }
        static void Main(string[] args)
        {
            SwapTwoNumbers stn = new SwapTwoNumbers();
            stn.Swap();
            Console.ReadLine();
        }
    }
}

Output

Before swap a=12 and b=56
After swap a=56 and b=12

Swap two numbers without using third variable in java

import java.util.*;
class SwapOfNumbers
{
	public void Swap()
	{
		int a=87,b=28;
		System.out.println("Before swap a="+a+" and b="+b);
		a=a+b;
		b=a-b;
		a=a-b;
		System.out.println("After swap a="+a+" and b="+b);
	}
}
class examples
{
public static void main(String[] args)
	{
    SwapOfNumbers son=new SwapOfNumbers();	
	son.Swap();
    }
}

Output

Before swap a=87 and b=28
After swap a=28 and b=87

Write a comment


Name Email Message