Computer Science, asked by RiyaVira13, 1 month ago

write a program to interchange the value of two numbers without using the third variable in Java​

Answers

Answered by anindyaadhikari13
8

\textsf{\large{\underline{Solution}:}}

The given problem is solved using language - Java.

import java.util.Scanner;

public class Brainly{

   public static void main(String s[]){

       Scanner sc=new Scanner(System.in);

       int a,b;

       System.out.print("Enter a: ");

       a=sc.nextInt();

       System.out.print("Enter b: ");

       b=sc.nextInt();

       System.out.println("Before Swapping:");

       System.out.println("a = "+a);

       System.out.println("b = "+b);

       a=a+b;

       b=a-b;

       a=a-b;

       System.out.println("After Swapping:");

       System.out.println("a = "+a);

       System.out.println("b = "+b);

   }

}

\textsf{\large{\underline{Explanation}:}}

To understand the program, lets take two values. Let -

> a = 5

> b = 6

After interchange, it should be -

> a = 6

> b = 5

But we cannot use third variable here. We have to utilise only these two variables for swapping.

Before Swapping,

> a = 5

> b = 6

Now,

> a = a + b

> a = 5 + 6 = 11

> a becomes 11.

Now,

> b = a - b

> b = 11 - 6

> b = 5  - Notice that 'b' now stores the value present in variable 'a'. Now, only variable 'a' is left to modify.

> a = a - b

> a = 11 - 5

> a = 6

Now, the values are swapped.!!

Hence, the problem is solved!

Attachments:
Similar questions