StreakPeaked· Practice

ExamsGATETechnical

The following function computes the maximum value contained in an integer array p[ ] of size n (n >= 1). int max(int *p, int n) { int a=0, b=n-1; while (__________) { if (p[a] <= p[b]) { a = a+1; } else { b = b-1; } } return p[a]; } The missing loop condition is

  1. a != n
  2. b != 0
  3. b > (a + 1)
  4. b != a

Correct answer: b != a

Solution

The loop condition 'b != a' ensures that the indices a and b do not cross each other, allowing the function to correctly compare elements from both ends of the array until the maximum value is found. This prevents the loop from terminating prematurely and guarantees that the maximum value is identified.

Related GATE Technical questions

⚔️ Practice GATE Technical free + battle 1v1 →