Computer Sciences > Gate 2016 Set-1 > Functions
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
A
a != n
B
b != 0
C
b > (a + 1)
D
b != a

Correct : F

Given:
A C function to find the maximum value in an integer array p[] of size n (where n ≥ 1):
Initial indices: a = 0, b = n - 1.
Inside the loop, if p[a] ≤ p[b], we do a = a + 1; otherwise, b = b - 1.
Finally, it returns p[a].
To find:
The missing loop condition.
Solution:
Let me understand what the algorithm is doing here.
We have two pointers, a at the start (index 0) and b at the end (index n - 1).
In each iteration, we compare p[a] and p[b].
If p[a] ≤ p[b], the element at a cannot be the strictly unique maximum, so we can safely eliminate it by incrementing a.
If p[a] > p[b], the element at b is definitely not the maximum, so we eliminate it by decrementing b.
So, in every iteration, the search window [a, b] shrinks by 1.
The maximum element will always remain inside the subarray from index a to b.
We need to stop when the search window contains exactly one element, that is, when a = b.
Once a = b, that single remaining element p[a] is our maximum value.
Therefore, the loop must continue as long as there is more than one element left, which means while a ≠ b (or b != a).
Let's check with an example: n = 1.
Initially a = 0, b = 0.
If the condition is b != a, 0 != 0 is false, the loop doesn't execute at all, and it directly returns p[0], which is correct for a single-element array.
Hence, the correct loop condition is b != a.
Answer:
(D) b != a

Similar Questions

Consider the following C program. void f(int, short); void main() { &nbsp; &nbsp; int i = 100; &nbsp; &nbsp; short s = 12; &nbsp; &nbsp; short *p = &s; &...
#144 MCQ
Consider the following function implemented in C: void printxy(int x, int y) { &nbsp; &nbsp; int *ptr; &nbsp; &nbsp; x = 0; &nbsp; &nbsp; ptr = &x;...
#159 MCQ
Consider the following program: int f(int *p, int n) { &nbsp; &nbsp; if (n
#545 Fill in the Blanks

Related Topics

maximum value array GATE CS 2016 Set-1 find maximum in array loop condition missing while loop computer science gate array traversal GATE set-1 questions

Unique Visitor Count

Total Unique Visitors

Loading......