Last Updated : 10 Apr, 2024

What is the output of the program

#include <iostream>
using namespace std;

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;
     }
     cout << 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.


Share your thoughts in the comments