Swap Two Numbers in Java
Q. Write a Java program to swap two numbers using a temp variable
import java.util.Scanner;
public class SwapWithTemp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input two numbers
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Display original values
System.out.println("Before swapping: num1 = " + num1 + ", num2 = " + num2);
// Swap using a temporary variable
int temp = num1;
num1 = num2;
num2 = temp;
// Display swapped values
System.out.println("After swapping: num1 = " + num1 + ", num2 = " + num2);
scanner.close();
}
}
Q. Write an algorithm to swap two numbers using a temp variable
1. Start 2. Read two numbers: num1 and num2 3. Store num1 in a temporary variable: temp = num1 4. Assign num2 to num1: num1 = num2 5. Assign temp to num2: num2 = temp 6. Print the swapped values 7. End
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com