Finding the day by days of week number – switch case – CSKC
Sign In

Search

Code Learning #CPP#1963    siteicon   siteicon  

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.

Source Code

TC++ #1963

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Alternate (?) :   Related ( ? ) :

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



Share

Created: 28-Dec-2017 00:16 | Updated: 15-Sep-2018 11:55|