Consider the following C program: #include<stdio.h> int main() { int i, j, k =…
2015
Consider the following C program:
#include<stdio.h> int main() { int i, j, k = 0; j=2 * 3 / 4 + 2.0 / 5 + 8 / 5; k-=--j; for (i=0; i<5; i++) { switch(i+k) { case 1: case 2: printf("\n%d", i+k); case 3: printf("\n%d", i+k); default: printf("\n%d", i+k); } } return 0; }The number of times printf statement is executed is ____________.
Attempted by 180 students.
Show answer & explanation
Correct answer: 10
Solution: step-by-step explanation to count printf executions.
Evaluate j: 2 * 3 / 4 + 2.0 / 5 + 8 / 5 = 6/4 + 0.4 + 1 = 1 + 0.4 + 1 = 2.4. Assigning to integer j truncates the fractional part, so j becomes 2.
Update k: --j decrements j to 1, returning 1; then k -= 1 sets k from 0 to -1.
Analyze the loop and switch behavior: i runs from 0 to 4. For each i compute i + k (with k = -1) and see which switch labels match. There are no break statements, so matching a case will fall through and execute all subsequent prints.
i = 0: i + k = -1. No case matches; default executes → 1 printf.
i = 1: i + k = 0. No case matches; default executes → 1 printf.
i = 2: i + k = 1. Matches the first listed case. Execution falls through to the prints in the following labels, so case for value 1 causes three prints (the prints at the case for value 2, the case for value 3, and default) → 3 printf calls.
i = 3: i + k = 2. Matches the second case; executes its printf and then falls through to case for value 3 and default → 3 printf calls.
i = 4: i + k = 3. Matches the third case; executes its printf and then falls through to default → 2 printf calls.
Total prints: 1 + 1 + 3 + 3 + 2 = 10. Therefore the printf statement is executed 10 times.
A video solution is available for this question — log in and enroll to watch it.