481 views
13 13 votes

What is the output of the following code?

#include <stdio.h>

int main() {
    int i, j, count = 0;

    for (i = 1; i <= 3; i++) {
        for (j = 1; j <= i; j++) {
            count = count + j;
        }
    }

    printf("%d", count);
    return 0;
}

2 Answers

4 4 votes

For $\texttt{i = 1}$, the inner loop runs for $\texttt{j = 1}$, so $\texttt{count = 0 + 1 = 1}$.

For $\texttt{i = 2}$, the inner loop runs for $\texttt{j = 1, 2}$, so $\texttt{count = 1 + 1 + 2 = 4}$.

For $\texttt{i = 3}$, the inner loop runs for $\texttt{j = 1, 2, 3}$, so $\texttt{count = 4 + 1 + 2 + 3 = 10}$.

Therefore, the output is $\texttt{10}$.

Answer:
Position:
Show:

Related questions

13 13 votes
1 1 answer
400
400 views
GO Classes asked Jun 3
400 views
What is the output of the following code?#include <stdio.h int main() { int i, j, sum = 0; for (i = 1; i <= 4; i++) { for (j = 1; j <= 4; j++) { if (j == i) continue; if ...
10 10 votes
1 1 answer
342
342 views
GO Classes asked Jun 3
342 views
What is the output of the following code?#include <stdio.h int main() { int x = 2, y = 0; switch (x) { case 1: y = y + 1; case 2: y = y + 2; case 3: y = y + 3; break; def...
11 11 votes
3 3 answers
459
459 views
GO Classes asked Jun 3
459 views
What is the output of the following code?#include <stdio.h int main() { int a = 1, b = 2, c = 3; if (a++ 1 && ++b 2 || c++ == 3) printf("%d %d %d", a, b, c); else print...
12 12 votes
2 2 answers
408
408 views
GO Classes asked Jun 3
408 views
What is the output of the following code?#include <stdio.h int main() { int x = 3, y = 4, z; z = x++ + ++y; printf("%d %d %d", x, y, z); return 0; }$\texttt{4\ 5\ 8}$ $\t...