Swap two numbers

In this article, we are going to swap two numbers by using two different approach. first approach is using third variable and second one is without using third variable.

Swapping two numbers using third variable.

In this approach, we used a temporary i.e. third variable two swaps two numbers. Here we are going to use java to implement the swapping of two numbers using a third variable.

Steps:-

  • Take first number input from user.
  • Take the second number input from the user.
  • Take the third variable temp to swap two numbers.
  • Now copy the value of first number to temp.
  • Now copy the value of second number to first number variable.
  • Now copy the value of temp to second number variable.
  • Now print both variables and value will be swapped.

Java code to swap number by using third variable:-

package gangforcode;
import java.util.Scanner;
public class SwapNo {

	public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	System.out.println("Enter first number");
	int num1=sc.nextInt();
	System.out.println("Enter second number");
	int num2=sc.nextInt();
	int temp=0;
	temp=num1;
	num1=num2;
	num2=temp;
	System.out.println("First number is  "+ num1);
	System.out.println("Second number is  "+ num2);
			
	
	}

}

Output:-

swapping of two numbers

Swapping of two numbers without using third variable:-

In this approach, we are going to swap two numbers without using any extra variable i.e. third variable. Here we are going to use java to swap two variables or numbers without using a third variable.

Steps:-

  • Take first number input from user.
  • Take the second number input from the user.
  • Add both variables and store in first variable.
  • subtract second variable from first variable and store result in second variable.
  • subtract second variable from first variable and store in first variable.
  • print both variables the value will be swap.

java code to swap two swap numbers without using third variable:-

package gangforcode;
import java.util.*;

public class SwapTwoNos {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter no 1");
		int num1= sc.nextInt();
		System.out.println("Enter no 2");
		int num2 = sc.nextInt();
		System.out.println("No before swapping \nnum1== "+ num1+"\nnum2= "+num2);
		
		num1=num1+num2;
		num2=num1-num2;
		num1=num1-num2;
		System.out.println("No after swapping ");
		System.out.println("num1= "+num1);
		System.out.println("num2= "+ num2);
		
		

	}

}

Output:-

swapping of two numbers in java

You can use same approach to swap two numbers in other programing languages like C, C++, python, etc.

Leave a Comment