adsense


Showing posts with label JAVA PROGRAM TO SWAP TWO NUMBERS. Show all posts
Showing posts with label JAVA PROGRAM TO SWAP TWO NUMBERS. Show all posts

Monday, 16 November 2015

JAVA PROGRAM TO SWAP TWO NUMBERS PAGE 17








COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



JAVA PROGRAM TO SWAP TWO NUMBERS








Java program to swap two numbers

This java program swaps two numbers using a temporary variable. 
To swap numbers without using extra variable see another code below.

Swapping using temporary or third variable

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);
   }
}
Swap numbers program class file.
Output of program:
 
Swapping without temporary variable
import java.util.Scanner;
 
class SwapNumbers
{
   public static void main(String args[])
   {
      int x, y;
      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);
 
      x = x + y;
      y = x - y;
      x = x - y;
 
      System.out.println("After Swapping\nx = "+x+"\ny = "+y);
   }
}