Open In App

GATE | GATE-CS-2016 (Set 1) | Question 44

Like Article
Like
Save
Share
Report

The following function computes the maximum value contained in an integer array p[] of size n (n >= 1) 
 

C




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
 


Answer: (D)

Explanation:

#include < iostream >
int max(int *p, int n)
{
    int a=0, b=n-1;
    while (a!=b)
    {
        if (p[a] <= p[b])
        {
            a = a+1;
        }
        else
        {
            b = b-1;
        }
    }
    return p[a];
}

int main()
{
   int arr[] = {10, 5, 1, 40, 30};
   int n = sizeof(arr)/sizeof(arr[0]);
   std::cout << max(arr, 5);
}


Quiz of this Question
Please comment below if you find anything wrong in the above post


Last Updated : 12 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads