Problem: -
- Write a program to swap a number using third variables.
- Write a program to swap a number without using third variables.
Solution: -
1. Write a program to swap a number using third variables.
import java.util.Scanner;
class swap {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scan.nextInt();
System.out.print("Enter second number: ");
int num2 = scan.nextInt();
System.out.println("\nBefore Swapping : \nFirst Number: " +num1+ "\nSecond Number: " +num2);
// swap number
int temp = num1;
num1 = num2;
num2 = temp;
System.out.println("\nAfter Swapping : \nFirst Number: " +num1+ "\nSecond Number: " +num2);
}
}
Output: -
2. Write a program to swap a number without using third variables.
import java.util.Scanner;
class swap1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scan.nextInt();
System.out.print("Enter second number: ");
int num2 = scan.nextInt();
System.out.println("\nBefore Swapping : \nFirst Number: " +num1+ "\nSecond Number: " +num2);
// swap number
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("\nAfter Swapping : \nFirst Number: " +num1+ "\nSecond Number: " +num2);
}
}
Output: -
Tags
Java