Skip to content
Related Articles
Open in App
Not now

Related Articles

C | Loops & Control Structure | Question 10

Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 06 Feb, 2013
Improve Article
Save Article
Like Article




# 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;
}


(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;
  }
My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!