Finding the day by days of week number – switch case – Computer Sir Ki Class

Code Learning #CPP#1963

## Finding the day by days of week number – switch case

User gives the day number and the program outputs the day name for five days and holiday for sat. and sun.

## Learning Objectives

• Understanding the operation of switch-case selection construct.
• Understanding the passing of integer value for switch case selection.
• Understanding break after each switch case.
• Understanding the fall through in switch case.
• Understanding the purpose of default case.

## Run Output

``````Enter the day number of week(1-7) : 1
Monday

-OR-
Enter the day number of week(1-7) : 7
HOLIDAY

-OR-
Enter the day number of week(1-7) : 8
Error in input``````

## Code Understanding

switch (d) {
The integer value of day value input is passed to switch.

case 1: cout <<“Monday”; break;
case 2: cout <<“Tuesday”;break;
case 3: cout <<“Wednesday”;break;
case 4: cout <<“Thursday”;break;
case 5: cout <<“Friday” ;break;
For first five cases from 1 to 5 the day name is output. after outputting each name a break is given so that program exits the switch selection and goes to line after the switch.

case 6:
case 7: cout <<“HOLIDAY” ;break;
For both case 6 and 7 value of day number, HOLIDAY is printed. This is also called fall through as condition at values 6 falls through the condition for next case at 7.

default: cout <<“Error in input”;
If none of cases finds a match, means the value given by user is not available from case 1 to 7 then this default case is executed.

## Notes

• Switch case can always  be implemented by if-else-if ladder.
• Its construct is like a single pole muti throw switch used on electrical circuits. Things like fan regulator, radio band switch use these kind of switching mechanism.

## Common Errors

• The break command in case statement is often missed by programmers. If it is not given then fall through action happens.
• Switch case bracket positions have to be properly remembered.
• The case <value>: syntax is often incorrectly written by using semicolon or comma.

Suggested Filename(s): daysofweek.cpp

sunmitra| Created: 28-Dec-2017 | Updated: 15-Sep-2018|

×