Consider the C program given below : C #include <stdio.h> int main () { int…

2007

Consider the C program given below :

C

 #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?

  1. A.

    9

  2. B.

    8

  3. C.

    7

  4. D.

    6

Attempted by 9 students.

Show answer & explanation

Correct answer: C

Explanation:

  • Initial values: sum = 0, maxsum = 0, array = {2, -2, -1, 3, 4, 2}.

  • i = 0, element = 2: i == 0 triggers the branch. sum is set to 2. maxsum remains 0.

  • i = 1, element = -2: element is negative, so the code updates maxsum to 2 (sum > maxsum) and resets sum to 0.

  • i = 2, element = -1: negative again, no change to maxsum (0 vs current sum 0), sum remains 0.

  • i = 3, element = 3: not negative and not less than previous element, so sum becomes 3.

  • i = 4, element = 4: continues the run, sum becomes 7 (3 + 4).

  • i = 5, element = 2: since 2 < 4 the code treats this as a break in the run, updates maxsum to 7 (sum > maxsum), and resets sum to 2.

  • After the loop the final check does not change maxsum (2 is not greater than 7).

Answer: 7

Explore the full course: Gate Guidance By Sanchit Sir