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]); }
Topic: Swapping without a third variable
Answer
(1) x[0] = x[0] * x[1]; (2) x[1] = x[0] / x[1];
Completed method:
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]); }
The final line is the clue: it divides, so the swap must be built from multiplication and division. Trace with x[0] = 4 and x[1] = 8: x[0] = 4 * 8 = 32 (x[0] now holds the product) x[1] = 32 / 8 = 4 (the old x[0] lands in x[1]) x[0] = 32 / 4 = 8 (the old x[1] lands in x[0]) Output: 8 4 — the two elements have exchanged places with no third variable. The addition-and-subtraction version (a = a + b; b = a - b; a = a - b;) works the same way and is safer, since the multiplication method fails if either value is 0. Mention that if you have room.