Write a program that accepts a month and a year (both in numbers) from the user
ID: 3819836 • Letter: W
Question
Write a program that accepts a month and a year (both in numbers) from the user and prints out the number of days in that month. Background: There are 31 days in January, March, May, July, August, October, or December, and 30 days in April, June, September, or November. If the year is a leap year, February has 29 days, otherwise it has 28 days. Any year that is evenly divisible by 4 is a leap year. For example, 1988, 1992, and 1996 are leap years. However, there is still a small error that must be accounted for. To eliminate this error, a year that is evenly divisible by 100 (for example, 1900 is a leap year only if it is also evenly divisible by 400. For this reason, the following years are not leap years: 1700, 1800, 1900, 2100 2200, 2300, 2500, 2600. This is because they are evenly divisible by 100 but not by 400. The following years are leap years: 1600, 2000, 2400. To determine if a number x is evenly divisible by another number y, in MATLAB, you can call a build-in function mod(x, y). If mod(x, y) is equal to 0, x is evenly divisible by y. For example, mod(1900, 100) is 0 and mod(1900, 4000 is 300.Explanation / Answer
//Matlab program to print number of days in given month..
% get the month and year
disp('Program to calculate number of days');
month = input('Enter the month (1-12): ');
year = input('Enter the year (yyyy): ');
% To check the leap year
if mod(year,400) == 0
leap_year =1;
elseif mod(year,100) ==0
leap_year =0;
elseif mod (year,4)==0
leap_year =1;
else
leap_year =0;
end
% calculate days in months
switch (i)
case (1,3,5,7,8,10,12),
days = 31;
case (4,6,9,11),
days =30;
case 2,
days=28 + leap_year;
end
%print the days
fprintf('The number of days in the month %2d is %2d days. ', month,days);
Output:
Program to calculate number of days
Enter the month (1-12): 6
Enter the year (yyyy): 1990
The number of days in the month 6 is 31 days.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.