316 views
8 8 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 <= 5; j++) {
            if (j % i == 0)
                continue;

            if (i + j > 6)
                break;

            sum = sum + i + j;
        }
    }

    printf("%d", sum);

    return 0;
}

2 Answers

2 2 votes

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

For $\texttt{i = 1}$:
Every value of $\texttt{j}$ is divisible by $\texttt{1}$, so $\texttt{continue}$ runs every time.
Nothing is added.
So, $\texttt{sum = 0}$.

For $\texttt{i = 2}$:
$\texttt{j = 1}$ is not divisible by $\texttt{2}$ and $\texttt{i + j = 3}$, so add $\texttt{2 + 1 = 3}$.
$\texttt{j = 2}$ is divisible by $\texttt{2}$, so skip.
$\texttt{j = 3}$ is not divisible by $\texttt{2}$ and $\texttt{i + j = 5}$, so add $\texttt{2 + 3 = 5}$.
$\texttt{j = 4}$ is divisible by $\texttt{2}$, so skip.
$\texttt{j = 5}$ is not divisible by $\texttt{2}$, but $\texttt{i + j = 7}$, so $\texttt{break}$ occurs.
Now, $\texttt{sum = 0 + 3 + 5 = 8}$.

For $\texttt{i = 3}$:
$\texttt{j = 1}$ is not divisible by $\texttt{3}$ and $\texttt{i + j = 4}$, so add $\texttt{3 + 1 = 4}$.
$\texttt{j = 2}$ is not divisible by $\texttt{3}$ and $\texttt{i + j = 5}$, so add $\texttt{3 + 2 = 5}$.
$\texttt{j = 3}$ is divisible by $\texttt{3}$, so skip.
$\texttt{j = 4}$ is not divisible by $\texttt{3}$, but $\texttt{i + j = 7}$, so $\texttt{break}$ occurs.
Now, $\texttt{sum = 8 + 4 + 5 = 17}$.

For $\texttt{i = 4}$:
$\texttt{j = 1}$ is not divisible by $\texttt{4}$ and $\texttt{i + j = 5}$, so add $\texttt{4 + 1 = 5}$.
$\texttt{j = 2}$ is not divisible by $\texttt{4}$, but $\texttt{i + j = 6}$ is not greater than $\texttt{6}$, so add $\texttt{4 + 2 = 6}$.
$\texttt{j = 3}$ is not divisible by $\texttt{4}$, but $\texttt{i + j = 7}$, so $\texttt{break}$ occurs.
Now, $\texttt{sum = 17 + 5 + 6 = 28}$.

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

Answer:
Position:
Show:

Related questions

7 7 votes
1 1 answer
205
205 views
GO Classes asked Jun 6
205 views
What is the output of the following code?#include <stdio.h int fun(int n) { if (n == 0) return 1; return n * fun(n - 2); } int main() { printf("%d", fun(6)); return 0; }
7 7 votes
1 1 answer
237
237 views
GO Classes asked Jun 6
237 views
What is the output of the following code?#include <stdio.h int solve(int n) { static int x = 1; if (n == 0) return x; x = x + n; return solve(n - 1); } int main() { print...
6 6 votes
1 1 answer
243
243 views
GO Classes asked Jun 6
243 views
What is the output of the following code?#include <stdio.h struct Student { int marks; }; void update(struct Student s) { s.marks = s.marks + 10; } int main() { struct St...
7 7 votes
1 1 answer
231
231 views
GO Classes asked Jun 6
231 views
What is the output of the following code?#include <stdio.h int main() { int a = 5, b = 10; int *p = &a; int q = &p; q = q + 3; p = &b; q = q + a; printf("%d %d", a, ...