Finding quarter of the year based on month – switch case
User inputs the month code from 1 to 12 and the output indicates the quarter of the month which it falls in.
Learning Objectives
- Learning multiple fall through in same switch-case construct.
- Understanding that each case in itself like block of code without writing the curly braces.
Source Code
|
Run Output
Code Understanding
case 1: case 2: case 3:
cout <<“First quarter of year”<<endl;
cout <<“Months: Jan-Feb-Mar”;
break;
This whole is one block of code. No curly braces are required here. The curly braces used for the switch itself define the scope of variables in this code. The individual case is itself a block of code as only one case or set of cases (in case of fall through) is supposed to be active. Multiple fall through can be built within the same switch-case construct.
Notes
- Declaration and initialisation of variables within the switch case are permitted only when code for a case is enclosed within curly braces.
Common Errors
- Forgetting the break statement is often a major cause of errors in this type of code.
Suggested Filename(s): year-quarter.cpp
sunmitra| Created: 28-Dec-2017 | Updated: 15-Sep-2018|