Back to Tutorials
Solved ProgramsICSEClass 9Computer Applications

Swapping numbers program

Write a program to swap two numbers using a temporary variable.

Trushna Tejwani17 January 2020
Solved Programs

Write a program to swap two numbers using a temporary variable.

public class swap1
{
    public static void main()
    {
        int temp;
        int a=3;
        int b=9;
        temp=a;
        a=b;
        b=temp;
        System.out.println("After swapping, a="+a);
        System.out.println("After swapping, b="+b);
    }

<tbody>

After swapping,a will be=9
After swapping,b will be=3

</tbody>

Write a program to swap two numbers without using a temporary variable.

public class swap2
{
    public static void main()
    {
        int a=3;
        int b=9;
        a=a+b;
        b=a-b;
        a=a-b;
       System.out.println("After swapping, a="+a);
       System.out.println("After swapping, b="+b);
    }

<tbody>

After swapping,a will be=9
After swapping,b will be=3

</tbody>

rite a program