KnowledgeBoat Logo

Computer Applications

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 = 76, b = 65

Sample Output: a = 65, b = 76

Java

Input in Java

46 Likes

Answer

import java.util.Scanner;

public class KboatNumberSwap
{
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        
        System.out.println("Please provide two unequal numbers");
        
        System.out.print("Enter the first number: ");
        int firstNum = in.nextInt();
        
        System.out.print("Enter the second number: ");
        int secondNum = in.nextInt();
        
        if (firstNum == secondNum) {
            System.out.println("Invalid Input. Numbers are equal.");
            return;
        }
        
        firstNum = firstNum + secondNum;
        secondNum = firstNum - secondNum;
        firstNum = firstNum - secondNum;
        
        System.out.println("First Number: " + firstNum);
        System.out.println("Second Number: " + secondNum);
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of 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 = 76, b = 65 Sample Output: a = 65, b = 76

Answered By

22 Likes


Related Questions