In: Computer Science
The following pseudocode describes a simple algorithm which swaps the values in two variables, x and y:
1 print “Enter initial value of x: ”
2 input x
3 print “Enter initial value of y: ”
4 input y
5 set temp to x
6 set x to y
7 set y to temp
8 print “x = ” x“, y = ” y
Write a Java Program that implements this algorithm.
program:
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int x,y,temp; //variable declaration
Scanner s = new Scanner(System.in); //to read input from user we
create this object s
System.out.println("Enter initial value of x "); //prompt user to
enter x value
x = s.nextInt(); //read x value from user
System.out.println("Enter initial value of y "); //prompt user
to enter y value
y = s.nextInt(); //read y value from user
//swapping values
temp=x;
x=y;
y=temp;
//after sapping
System.out.println("After swapping: x= "+x +" y=" + y);
System.out.println( );
}
}
output: