Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

GATE | Gate IT 2007 | Question 31

  • Last Updated : 28 Jun, 2021

Consider the C program given below :

Attention reader! Don’t stop learning now.  Practice GATE exam well before the actual exam with the subject-wise and overall quizzes available in GATE Test Series Course.

Learn all GATE CS concepts with Free Live Classes on our youtube channel.




#include <stdio.h>
int main ()    {
    int sum = 0, maxsum = 0,  i,  n = 6;
    int a [] = {2, -2, -1, 3, 4, 2};
    for (i = 0; i < n; i++)    {
            if (i == 0 || a [i]  < 0  || a [i] < a [i - 1])  {
                     if (sum > maxsum) maxsum = sum;
                     sum = (a [i] > 0) ? a [i] : 0;
            }
            else sum += a [i];
    }
    if (sum > maxsum) maxsum = sum ;
    printf ("%d\n", maxsum);
  

What is the value printed out when this program is executed?
(A) 9
(B) 8
(C) 7
(D) 6


Answer: (C)

Explanation: If you look for loop carefully, you will notice that it assigns sum variable to some value in if condition and increments it in the else condition. On further thought, it would be clear that this loop stores sum of increasing subsequence of positive integers in sum variable and max of sum in maxsum. Hence, maxsum – maximum sum of increasing subsequence of positive integers will get printed out when this program is executed, which is 3 + 4 = 7.

This solution is contributed by Vineet Purswani



//output will be 3+4 =7 {for || if 1st argument is true 2nd argument will not be calculated, and if 1st argument is false, 2nd argument will be calculated}

Another Solution

When i=1

-> i==0 is false, but a[i] maxsum) is true, since sum=2 and maxsum=0.So maxsum=2. sum = (a [i] > 0) ? a [i] : 0; , sum=0 since a[i]<0.

When i=2

-> i==0 is false, a[i] maxsum) is false, since sum=0 and maxsum=2.Since sum = (a [i] > 0) ? a [i] : 0; , sum=0 since a[i]<0.

When i=3

-> i==0 is false , a[i]<0 is false and a [i] < a [i – 1] is false so condition (1) is false. Now sum += a [i] = 3.

When i=4

-> i==0 is false , a[i]<0 is false and a [i] < a [i – 1] is false so condition (1) is false. Now sum += a [i] = 7.

When i=5

-> i==0 is false , a[i]<0 is false and a [i] maxsum is true, since sum=7 and maxsum=2,so maxsum=7.Since sum =

(a [i] > 0) ? a [i] : 0, so sum=2 since a[5]>0.

This solution is contributed by nirmal Bharadwaj

Quiz of this Question

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!