The program allows users to input two numbers and then swaps the values of these two numbers.
It provides a practical illustration of how to exchange the values of two variables in a program
In this program:
- User Input: Prompt the user to enter two numbers (a and b).
- Swapping: Swap the values of a and b using a temporary variable (temp).
- Display Results: Show the values of a and b both before and after the swap.
import java.util.Scanner; public class SwapValues { public static void main(String[] args) { int a, b, temp; Scanner scanner = new Scanner(System.in); System.out.print("Enter 1st number: "); a = scanner.nextInt(); System.out.print("Enter 2nd number: "); b = scanner.nextInt(); System.out.println("\nBefore Swapping..."); System.out.println("A=" + a + ", B=" + b); temp = a; a = b; b = temp; System.out.println("\nAfter Swapping..."); System.out.println("A=" + a + ", B=" + b); } }
Follow Us