Finding the day by days of week number – if else – Computer Sir Ki Class

Code Learning #CPP#1968

## 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.

## 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

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

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

×