Computer Science, asked by arghya2005, 1 year ago

Write a JAVA program to input two unequal numbers. Display the numbers after swapping their values in the variables without using a third variable.

Answers

Answered by Anonymous
195

CODE:


import java.util.*;

class Swapping

{

public static void main(String args[])

{

Scanner sc=new Scanner(System.in);

System.out.println("Enter 2 numbers");

int a=sc.nextInt();

int b=sc.nextInt();

a=a+b;

b=a-b;

a=a-b;

System.out.println("Swapped value of a :"+b);

System.out.println("Swapped value of b :"+a);

}

}


LOGIC:

First note the step :

a = a + b

Then b = a - b

= > b = a + b - b [ from above ]

= > b = a

then a = a - b

= > a = a  - (  a - b )

= > a = a - a + b

= > a = b


That is the way they are swapped !


arghya2005: Thank you very much
Anonymous: welcome :-)
Answered by atrs7391
7

package com.company;

/* Write a program to input two unequal numbers. Display the numbers after swapping their values in  the variables without using a third variable.

Sample Input: a=23, b=56

Sample Output: a=56, b=23

*/

import java.util.Scanner;

public class Main {

   public static void main(String[] args) {

       Scanner sc = new Scanner (System.in);

       System.out.println("Enter Number a:");

       int a = sc.nextInt();

       System.out.println("Enter Number b:");

       int b = sc.nextInt();

       if (a!=b){

           a = a+b;

           b = a-b;

           a = a-b;

       }

       System.out.println("a = "+a+"    b = "+b);

   }

}

Similar questions