383 views
13 13 votes

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 (i + j > 5)
                break;

            sum = sum + i + j;
        }
    }

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

1 Answer

4 4 votes

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

For $\texttt{i = 1}$,
$\texttt{j = 1}$ is skipped because $\texttt{j == i}$.
Then values added are $\texttt{1 + 2}$, $\texttt{1 + 3}$, and $\texttt{1 + 4}$.
So, $\texttt{sum = 0 + 3 + 4 + 5 = 12}$.

For $\texttt{i = 2}$,
$\texttt{j = 1}$ adds $\texttt{2 + 1 = 3}$,
$\texttt{j = 2}$ is skipped, and $\texttt{j = 3}$ adds $\texttt{2 + 3 = 5}$.
For $\texttt{j = 4}$, $\texttt{i + j = 6}$, so $\texttt{break}$ occurs.
Now, $\texttt{sum = 12 + 3 + 5 = 20}$.

For $\texttt{i = 3}$,
$\texttt{j = 1}$ adds $\texttt{3 + 1 = 4}$, and $\texttt{j = 2}$ adds $\texttt{3 + 2 = 5}$.
Then $\texttt{j = 3}$ is skipped because $\texttt{j == i}$.
For $\texttt{j = 4}$, $\texttt{i + j = 7}$, so $\texttt{break}$ occurs.
Now, $\texttt{sum = 20 + 4 + 5 = 29}$.

For $\texttt{i = 4}$,
$\texttt{j = 1}$ adds $\texttt{4 + 1 = 5}$.
For $\texttt{j = 2}$, $\texttt{i + j = 6}$, so $\texttt{break}$ occurs.
Now, $\texttt{sum = 29 + 5 = 34}$.

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

Answer:
Position:
Show:

Related questions

13 13 votes
2 2 answers
463
463 views
GO Classes asked Jun 3
463 views
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; } } ...
10 10 votes
1 1 answer
318
318 views
GO Classes asked Jun 3
318 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
434
434 views
GO Classes asked Jun 3
434 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
379
379 views
GO Classes asked Jun 3
379 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...