- 08. Using switch case concepts, make a program that asks the user the month (number 1 through 12), and tells you how many days that month has. February has 28 days (not leap year).
How many days are there in the month
Come on.Months with 28 days: 2Months with 30 days: 4, 6, 9 and 11Months with 31 days: 1, 3, 5, 7, 8, 10 and 12
Let's do accumulating cases so you can better fix this important switch technique.
The days variable starts with 0.
The logic is as follows ... every month has 28 days or more. So we want case 2 to always run so it will be down there.
There we will add the value 28 to the days variable.
Okay, any month you enter will be at 28 days, because we will not use break in cases, to accumulate.
- days = days + 28;
The middle cases are the months 4, 6, 9 and 11 have 30 days.
As we will added 28 days, we only have to add 2 more days to stay 30, in these cases:
- days = days + 2;
You see: if you type 2, it falls only in case 2, which puts 28 in the days variable. If you type 4, 6, 9 or 11, it falls into those cases that add up to 2 and then falls into the case that adds up to 28 days, totaling 30 days.
So if you type 1, 3, 5, 7, 8, 10, or 12, we should just add +1:
- days = days + 1;
#include <iostream> using namespace std; int main() { int days=0, month; cout << "Month number: "; cin >> month; switch(month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = days + 1; case 4: case 6: case 9: case 11: days = days + 2; case 2: days=days+28; break; default: cout <<"Invalid month"<<endl; } cout <<"Month "<<month<<" has "<<days<<" days.\n"; }
Can you understand? It is a very charming solution.
Leap Year solution
- 09. Using switch case concepts, make a program that asks the user the month (number 1 through 12), and tells you how many days that month has, including whether it is a leap year or not.
Here, in addition to what is in the previous code, we have to ask the year to the user. If it is leap year, we should add 29 in case 2 to the days variable, if not, we keep adding only 28.
We do this with an IF ELSE statement internal to the switch case.
Here's how the code looks:
#include <iostream> using namespace std; int main() { int days=0, month, year; cout << "Month number: "; cin >> month; cout << "Year: "; cin >> year; switch(month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = days + 1; case 4: case 6: case 9: case 11: days = days + 2; case 2: if( (year % 400 == 0) || ( (year % 4 == 0) && (year % 100 != 0) ) ) days = days+29; else days = days+28; break; default: cout <<"Invalid month"<<endl; } cout <<"The month "<<month<<" has "<<days<<" days.\n"; }
No comments:
Post a Comment