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 _______.
View worked solution
Answer: 10
To find the number of times the printf statement is executed, we trace the program step-by-step:
Step 1: Calculate the initial values of and
2 * 3 / 4evaluates to6 / 4 = 1(integer division).2.0 / 5evaluates to0.4(floating-point division).8 / 5evaluates to1(integer division).- Thus, . Since is of type
int, it is truncated to . - Next,
k -= --jdecrements to first, then .
Step 2: Trace the loop for to
The switch expression is . Since there are no break statements, execution falls through to subsequent cases once a match is found:
| Matching Case & Fall-through Path | printf Executions |
||
|---|---|---|---|
| 0 | -1 | default |
1 |
| 1 | 0 | default |
1 |
| 2 | 1 | case 1 → case 2 → case 3 → default |
3 |
| 3 | 2 | case 2 → case 3 → default |
3 |
| 4 | 3 | case 3 → default |
2 |
Total Executions: .
Free practice · Your answers on this page are not saved.
