Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

MATLAB Question The Gregorian calendar, which is the most widely used kind in th

ID: 3769384 • Letter: M

Question

MATLAB Question

The Gregorian calendar, which is the most widely used kind in the world, has a special mechanism called leap years, in which an additional day is included to keep the calendar synchronized with the astronomical year. The year y is a leap year if and only if y is divisible by 4 and not divisible by 100, or is divisible by 400.

(a) Write a MATLAB function that inputs a year and returns the logical 0 (i.e., false) if it is not a leap year and returns the logical 1 (i.e., true) if it is a leap year.

(b) Write a MATLAB program that uses your function to count how many leap years there are between years 2001 and 2400.

(c) Calculate the average number of days per year between 2001 and 2400.

(d) Knowing that January 1, 2001 was Monday, write a program that counts how many Friday the 13th you have between 2001 and 2400. Does it happen more frequently than the 13th of a month being any other days of the week?

Explanation / Answer

Completed items a,b and c

function result = isLeapYear(year)
% The year y is a leap year if and only if y is divisible by 4 and not divisible by 100, or is divisible by 400
    if((rem(year, 4) ==0 && rem(year, 100) != 0) || ( rem(year, 100) == 0 && rem(year, 400) == 0))
        result = 1
    else
        result = 0
    end
end

function result = countLeapYears(startY, endY)
    result = 0
    for year= startY : endY

        if(isLeapYear(year) == 1)
            result = result+1
        end
    end
end

% Calculate the average number of days per year between 2001 and 2400.

function result = averageDays(startY, endY)
    result = 0
    total = 0
    count = endY - startY +1
    for year= startY : endY
        total = total + 365
        % if leap year add another day so 366 days
        if(isLeapYear(year) == 1)
            total = total+1
        end
    end
    result = total/ count
end

isLeapYear(2015)
isLeapYear(2016)
countLeapYears(2001,2400)
averageDays(2001,2400)

-------------------output--------------------

Executing the program....
$octave -qf --no-window-system main.m