write a program in java to swap two numbers using third variable.
Answers
Explanation:
import java.util.*;
class Swap_With {
public static void main(String[] args) {
int x, y, t;// x and y are to swap
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of X and Y");
x = sc.nextInt();
y = sc.nextInt();
System.out.println("before swapping numbers: "+x +" "+ y);
/*swapping */
t = x;
x = y;
y = t;
System.out.println("After swapping: "+x +" " + y);
System.out.println( );
}
}
Answer:
Explanation:
import java.util.Scanner;
class SwapNumbers
{
public static void main(String args[])
{
int x, y, temp;
System.out.println("Enter x and y");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
temp = x;
x = y;
y = temp;
System.out.println("After Swapping\nx = "+x+"\ny = "+y);
}
}