MATLAB: Write a function, using arrays-vectors,’ input’& ‘fprintf’,’if’ statement’, ‘end’, ‘fgetl’ etc with good programming practices…like putting comments %

doit4mefgetlfprintffunction handlefunctionshomeworkinputMATLABnested functionsno attemptprogramming

*Task 3 [Intermediate] 2 marks*
(a) Write a function that accepts a year as input and determines whether it is a leap year. The function should return 1 if the year is a leap year, otherwise return 0.
The rules for determining leap years are as follows:
1) All years evenly divisible by 400 are leap years
2) Years evenly divisible by 100 but not by 400 are NOT leap years
3) Years divisible by 4 but not 100 are leap years
4) All other years are NOT leap years
For example, 1800, 1900, 2100 are not leap years. 2000, 2004 and
2400 are leap years.
*HINT*: You may want to use the mod function and if statements
(b) Write a MATLAB program that asks the user for the month (1 to 12) and the year then prints the number of days in the month, taking leap years into account by reusing the function you wrote for part (a). For example, if the user enters 2 (February) and 2004 (leap year), the program should print 29.
*HINT*: You may want to try switch statements (help switch)

Best Answer

The formula given there for leap years is wrong, so it is not possible to write a correct leap year program based upon the given specifications.
Let's be precise: nowadays, your answer is right, but only since Gregorian reform, which has been take into account at different times in different countries. Before that, and since 45BC, there was a leap year in every year divisible by 4 (NOTE: 45BC is year -44).
Even that isn't exactly true... At the beginning people did not understand what "once in 4 years" meant, and there was a period (between 45BC and 9BC) where there was a leap year every 3 years. Followed by a period (between 8BC and 8AD) where there was no leapyear at all.