Q:

Java program to swap two numbers with and without using third variable

belongs to collection: Java Basic Programs

0

Given two integer numbers and we have to swap them with and without using third variable.

Swapping of two numbers program is very common and important program, Here we are implementing this program in Java using two methods:

  1. Using third variable
    Here, we will use a temporary variable to swap the numbers.
  2. Without using third variable
    Here we will not use any temporary variable to swap the numbers.
  3.  

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the programs:

1) Swapping of numbers using third variable

//Java program to swap two numbers.
import java.util.*;

class SwapTwoNumbers
{
	public static void main(String []s)
	{
		int a,b;
		//Scanner class to read value
		Scanner sc=new Scanner(System.in);

		System.out.print("Enter value of a: ");
		a=sc.nextInt();
		System.out.print("Enter value of a: ");
		b=sc.nextInt();

		System.out.println("Before swapping - a: "+ a +", b: " + b);
		////using thrid variable
		int temp;
		temp=a;
		a=b;
		b=temp;
		//////////////////////
		System.out.println("After swapping  - a: "+ a +", b: " + b);
	}
}

Output

Enter value of a: 10
Enter value of a: 20
Before swapping - a: 10, b: 20
After swapping  - a: 20, b: 10

2) Swapping of numbers without using third variable

import java.util.*;

class SwapTwoNumbers
{
	public static void main(String []s)
	{
		int a,b;
		//Scanner class to read value
		Scanner sc=new Scanner(System.in);

		System.out.print("Enter value of a: ");
		a=sc.nextInt();
		System.out.print("Enter value of a: ");
		b=sc.nextInt();

		System.out.println("Before swapping - a: "+ a +", b: " + b);
		////without using thrid variable
		a=a+b;
		b=a-b;
		a=a-b;
		//////////////////////
		System.out.println("After swapping  - a: "+ a +", b: " + b);
	}
}

Output

Enter value of a: 10
Enter value of a: 20
Before swapping - a: 10, b: 20
After swapping  - a: 20, b: 10

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to print uppercase and lowercase alph... >>
<< Java program to check whether input number is EVEN...