Computer Applications

The following program segment swaps the first element and the second element of the given array without using the third variable, fill in the blanks with appropriate java statements:

void swap()
{ int x[] = {4, 8, 19, 24, 15};
(1) ............... ;
(2) ............... ;
x[0] = x[0] / x[1];
System.out.println(x[0] + " " + x[1]); }

Java Arrays

2 Likes

Answer

void swap()
{ int x[] = {4, 8, 19, 24, 15};
x[0] = x[0] * x[1];
x[1] = x[0] / x[1];
x[0] = x[0] / x[1];
System.out.println(x[0] + " " + x[1]); }

Explanation

The first two elements of the array are:

  • x[0] = 4
  • x[1] = 8

The swapping is done without using a third variable by using multiplication and division.

Step 1

x[0] = x[0] * x[1];

So,

x[0] = 4 * 8 = 32

Now:

  • x[0] = 32
  • x[1] = 8

Step 2

x[1] = x[0] / x[1];

So,

x[1] = 32 / 8 = 4

Now:

  • x[0] = 32
  • x[1] = 4

Step 3

x[0] = x[0] / x[1];

So,

x[0] = 32 / 4 = 8

Now:

  • x[0] = 8
  • x[1] = 4

Thus, the values of the first and second elements are interchanged.

Output

8 4

Answered By

1 Like


Related Questions