Advertisements
Advertisements
Question
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/I]): }Very Long Answer
Advertisements
Solution
(1) x[0] = x[0] * x[1];
(2) x[1] = x[0] / x[1];
The goal is to swap the first element x[0] (value 4) and the second element x[1] (value 8) without a temporary variable.
- Step 1: Multiply the two numbers and store the result in the first position: x[0] = 4 × 8 = 32.
- Step 2: Divide the new x[0] by the original x[1] to get the original x[0] and store it in x [1]: x[x] = 32/8 = 4.
- Step 3: (Already in image): Divide the total product by the new x[1] to get the original x[1] and store it in x[0] = 32/4 = 8.
shaalaa.com
Is there an error in this question or solution?
2025-2026 (March) Official Board Paper
