Finding the day by days of week number – if else – CSKC
Sign In

Search

Code Learning #CPP#1968    siteicon   siteicon  

Finding the day by days of week number – if else

User gives the day number and the program outputs the day name for five days and holiday for sat. and sun. using the if else logic instead of switch case

Learning Objectives

  • Understanding the switch-case replacement with the if-else-if ladder.

Source Code

TC++ #1968

 

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

if(d==1) cout<<“Monday”;
else if(d==2) cout <<“Tuesday”;
else if(d==3) cout <<“Wednesday”;
else if(d==4) cout <<“Thursday”;
else if(d==5) cout <<“Friday”;

For first five cases from 1 to 5 re checked with if else ladder and the day name is output. No break is required here like a switch-case construct as each item after the first one is in else-if condition.

else if(d==6 || d==7) cout <<“HOLIDAY”;
For both case 6 and 7 value of day number, HOLIDAY is printed. The fall through of switch-case is implemented here as multiple comparison check.

else 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 else  is executed. This is like the default case of switch.

Notes

  • Switch case can always  be implemented by if-else-if ladder but vice-versa is not always true.

Common Errors

  • Proper if-else-if construct removes the need of break in switch case. The break may be there for other reasons required by the program.


Suggested Filename(s): daysofweek-ifelse.cpp



Share

Created: 28-Dec-2017 00:34 | Updated: 15-Sep-2018 11:56|