wiz-icon
MyQuestionIcon
MyQuestionIcon
1
You visited us 1 times! Enjoying our articles? Unlock Full Access!
Question

Consider the C program given below:

# 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
No worries! We‘ve got your back. Try BYJU‘S free classes today!
B
6
No worries! We‘ve got your back. Try BYJU‘S free classes today!
C
8
No worries! We‘ve got your back. Try BYJU‘S free classes today!
D
7
Right on! Give the BNAT exam to get a 100% scholarship for BYJUS courses
Open in App
Solution

The correct option is D 7
Syntax error in above code segment. Right code given below:

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

Simply execute and trace value of sum and maxsum for i = 0 to 5

i initially 0 1 2 3 4 5

sum 0 0 2 0 3 7 2
maxsum 0 0 2 2 2 2 7

So, maxsum = 7

flag
Suggest Corrections
thumbs-up
0
Join BYJU'S Learning Program
similar_icon
Related Videos
thumbnail
lock
Adaptive Q18
MATHEMATICS
Watch in App
Join BYJU'S Learning Program
CrossIcon