C | Loops & Control Structure | Question 10
# include <stdio.h> int main() { int i = 0; for (i=0; i<20; i++) { switch(i) { case 0: i += 5; case 1: i += 2; case 5: i += 5; default: i += 4; break; } printf("%d ", i); } return 0; } |
chevron_right
filter_none
(A) 5 10 15 20
(B) 7 12 17 22
(C) 16 21
(D) Compiler Error
Answer: (C)
Explanation: Initially i = 0. Since case 0 is true i becomes 5, and since there is no break statement till last statement of switch block, i becomes 16. Now in next iteration no case is true, so execution goes to default and i becomes 21.
In C, if one case is true switch block is executed until it finds break statement. If no break statement is present all cases are executed after the true case. If you want to know why switch is implemented like this, well this implementation is useful for situations like below.
switch (c)
{
case 'a':
case 'e':
case 'i' :
case 'o':
case 'u':
printf(" Vowel character");
break;
default :
printf("Not a Vowel character");; break;
}
Recommended Posts:
- C | Loops & Control Structure | Question 3
- C | Loops & Control Structure | Question 4
- C | Loops & Control Structure | Question 5
- C | Loops & Control Structure | Question 6
- C | Loops & Control Structure | Question 7
- C | Loops & Control Structure | Question 20
- C | Loops & Control Structure | Question 8
- C | Loops & Control Structure | Question 9
- C | Loops & Control Structure | Question 19
- C | Loops & Control Structure | Question 12
- C | Loops & Control Structure | Question 13
- C | Loops & Control Structure | Question 14
- C | Loops & Control Structure | Question 15
- C | Loops & Control Structure | Question 17
- C | Loops & Control Structure | Question 21


