KnowledgeBoat Logo

Computer Applications

Consider the following program segment in which the statements are jumbled, choose the correct order of statements to swap two variables using the third variable.

void swap(int a, int b)
{	
  a = b;(1)
  b = t;(2)
  int t = 0;(3)
  t = a;(4)
}
  1. (1) (2) (3) (4)
  2. (3) (4) (1) (2)
  3. (1) (3) (4) (2)
  4. (2) (1) (4) (3)

Values & Data Types Java

ICSE Sp 2025

1 Like

Answer

(3) (4) (1) (2)

Reason — To swap two variables a and b using a third variable t, the correct sequence of statements is:

Step 1: Declare and initialize the third variable t.

int t = 0;  // (3)

Step 2: Assign the value of a to t.

t = a;  // (4)

Step 3: Assign the value of b to a.

a = b;  // (1)

Step 4: Assign the value of t (original value of a) to b.

b = t;  // (2)

Correct Order:

int t = 0;  // (3)
t = a;      // (4)
a = b;      // (1)
b = t;      // (2)

Answered By

1 Like


Related Questions