no1
and no2
) to hold the input values.
temp
) to temporarily store the value of one variable during the swap.
no1
to temp
.
no1
to no1
.
temp
to no2
.
no1
and no2
after swapping.
public class SwapNumbers
{
public static void main(String[] args)
{
int no1=22, no2=33;
// Display numbers before swapping
System.out.println("Before swapping: no1 = " + no1 + ", no2 = " + no2);
// Swap using a third variable
int temp = no1;
no1 = no2;
no2 = temp;
// Display numbers after swapping
System.out.println("After swapping: no1 = " + no1 + ", no2 = " + no2);
}
}
Before swapping: a = 22, b = 33 After swapping: a = 33, b = 22
import java.util.Scanner;
public class SwapNumbers
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
// Take input from the user
System.out.print("Enter the first number (no1): ");
int no1 = scanner.nextInt();
System.out.print("Enter the second number (no2): ");
int no2 = scanner.nextInt();
// Display numbers before swapping
System.out.println("Before swapping: no1 = " + no1 + ", no2 = " + no2);
// Swap using a third variable
int temp = no1;
no1 = no2;
no2 = temp;
// Display numbers after swapping
System.out.println("After swapping: no1 = " + no1 + ", no2 = " + no2);
// Close the scanner
scanner.close();
}
}
Enter the first number (a): 100 Enter the second number (b): 200 Before swapping: a = 100, b = 200 After swapping: a = 200, b = 100
no1
and no2
) to hold the input values.
a = a + b
b = a - b
a = a - b
no1
and no2
after swapping.
public class SwapNumbers2
{
public static void main(String[] args)
{
int no1=33, no2=44;
// Display numbers before swapping
System.out.println("Before swapping: no1 = " + no1 + ", no2 = " + no2);
// Swap without using a third variable
no1 = no1 + no2;
no2 = no1 - no2;
no1 = no1 - no2;
// Display numbers after swapping
System.out.println("After swapping: no1 = " + no1 + ", no2 = " + no2);
}
}
Before swapping: no1 = 33, no2 = 44 After swapping: no1 = 44, no2 = 33
import java.util.Scanner;
public class SwapNumbers2
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
// Take input from the user
System.out.print("Enter the first number (no1): ");
int no1 = scanner.nextInt();
System.out.print("Enter the second number (no1): ");
int no2 = scanner.nextInt();
// Display numbers before swapping
System.out.println("Before swapping: no1 = " + no1 + ", no2 = " + no2);
// Swap without using a third variable
no1 = no1 + no2;
no2 = no1 - no2;
no1 = no1 - no2;
// Display numbers after swapping
System.out.println("After swapping: no1 = " + no1 + ", no2 = " + no2);
// Close the scanner
scanner.close();
}
}
Enter the first number (no1): 555 Enter the second number (no1): 888 Before swapping: no1 = 555, no2 = 888 After swapping: no1 = 888, no2 = 555
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.