GATE | Gate IT 2007 | Question 31

Consider the C program given below :

filter_none

edit
close

play_arrow

link
brightness_4
code

#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);
  

chevron_right


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
Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.