What is the output of the following C program? #include <stdio.h> int main() {…
2018
What is the output of the following C program?
#include <stdio.h>
int main()
{
int index;
for (index = 1; index <= 5; index++)
{
printf("%d", index);
if (index == 3)
continue;
}
}Answer: B. 12345 — ConceptWithin one loop iteration, statements execute in source order. A continue statement skips only the statements that follow it in the current loop body,…
- A.
1245
- B.
12345
- C.
12245
- D.
12354
Attempted by 867 students.
Show answer & explanation
Correct answer: B
Concept
Within one loop iteration, statements execute in source order. A continue statement skips only the statements that follow it in the current loop body, then control moves to the loop update expression.
Application
At index = 1, printf emits 1; the condition is false; the update makes index = 2.
At index = 2, printf emits 2; the condition is false; the update makes index = 3.
At index = 3, printf emits 3 before the condition is tested; continue then transfers control to the update, which makes index = 4.
At index = 4, printf emits 4; the condition is false; the update makes index = 5.
At index = 5, printf emits 5; after the update makes index = 6, the loop condition fails.
Cross-check
If printf appeared after the if/continue block, the index = 3 iteration would skip printing. Here printf appears first, so that value has already been emitted before continue runs.
Therefore, the output is 12345.
A video solution is available for this question — log in and enroll to watch it.