303 views
5 5 votes

What is the output of the following code?

#include <stdio.h>

int main() {
    int a[5] = {2, 4, 1, 3, 5};
    int i, sum = 0;

    for (i = 0; i < 5; i++) {
        if (a[i] % 2 == 0)
            sum = sum + a[i];
        else {
            sum = sum + i;

            if (sum > 8)
                break;
        }
    }

    printf("%d %d", i, sum);
    return 0;
}
  1. $\texttt{3\ 11}$
     
  2. $\texttt{4\ 16}$
     
  3. $\texttt{5\ 16}$
     
  4. $\texttt{2\ 8}$

2 Answers

2 2 votes

Initially, $\texttt{sum = 0}$.

For $\texttt{i = 0}$, $\texttt{a[0] = 2}$, which is even. So, $\texttt{sum = 0 + 2 = 2}$.

For $\texttt{i = 1}$, $\texttt{a[1] = 4}$, which is even. So, $\texttt{sum = 2 + 4 = 6}$.

For $\texttt{i = 2}$, $\texttt{a[2] = 1}$, which is odd. So, $\texttt{sum = 6 + 2 = 8}$. Since $\texttt{sum > 8}$ is false, the loop continues.

For $\texttt{i = 3}$, $\texttt{a[3] = 3}$, which is odd. So, $\texttt{sum = 8 + 3 = 11}$.

Now $\texttt{sum > 8}$ is true, so $\texttt{break}$ is executed.

Therefore, the loop stops at $\texttt{i = 3}$ and $\texttt{sum = 11}$.

Answer: A. $\texttt{3\ 11}$

Answer:
Position:
Show:

Related questions

9 9 votes
2 2 answers
372
372 views
GO Classes asked Jun 5
372 views
What is the output of the following code?#include <stdio.h int main() { int a = 10, b = 20; int *p, *q; p = &a; q = &b; *p = *p + 5; *q = *p + *q; p = q; *p = *p - 10; pr...
8 8 votes
3 3 answers
334
334 views
GO Classes asked Jun 5
334 views
What is the output of the following code?#include <stdio.h int main() { int x = 3, y = 1; switch (x - 1) { case 1: y = y + 2; case 2: y = y * 3; case 3: y = y - 1; break;...
5 5 votes
2 2 answers
256
256 views
GO Classes asked Jun 5
256 views
What is the output of the following code?#include <stdio.h int main() { int i, j, count = 0; for (i = 1; i <= 4; i++) { for (j = 1; j <= 4; j++) { if (i == j) continue; i...
3 3 votes
2 2 answers
271
271 views
GO Classes asked Jun 5
271 views
What is the output of the following code?#include <stdio.h int update(int x) { x = x + 3; return x * 2; } int main() { int a = 4, b; b = update(a); printf("%d %d", a, b);...