C | Loops & Control Structure | Question 10





# include <stdio.h>
int main()
   int i = 0;
   for (i=0; i<20; i++)
       case 0:
         i += 5;
       case 1:
         i += 2;
       case 5:
         i += 5;
         i += 4;
     printf("%d  ", i);
   return 0;


(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");
    default :
      printf("Not a Vowel character");; break;

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up