Computer Science, asked by anuj1151, 11 months ago

Swap two numbers without using third variable in java

Answers

Answered by kuwarizainab
4
Java

// Program to swap two numbers  without 

// using temporary variable

import java.*;

  

class Geeks {

  

    public static void main(String a[])

    {

        int x = 10;

        int y = 5;

        x = x + y;

        y = x - y;

        x = x - y;

        System.out.println("After swaping:"

             + " x = " + x + ", y = " + y);

    }

}

  

// This code is contributed by Sam007


Answered by atrs7391
0

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