# How can I compute the leap years?

79 views (last 30 days)
Aaron Grubbs on 6 Oct 2017
Edited: Walter Roberson on 6 Oct 2017
function leapyr = leapyears(startYear, endYear)
%UNTITLED8 Summary of this function goes here
% Detailed explanation goes here
leapyr = 0;
i = 0;
for i = startYear:4:endYear
if mod(startYear, 4) == 0 && mod(endYear, 4) == 0
fprintf('%i \n', startYear)
elseif mod(startYear, 400) == 0 && mod(endYear, 400) == 0
fprintf('%i \n', startYear)
else mod(startYear, 100) == 0 && mod(endYear, 100) == 0
fprintf('%i \n', startYear)
end
end
end
Hey all, I'm struggling to figure out how I'm supposed to supposed to print a list of leap years given two inputs.
The output is supposed to look like this:
a. Example 1.
>> leapyears(2004,2016)
2004
2008
2012
2016
b. Example 2.
>> leapyears(1881,1907)
1884
1888
1892
1896
1904

#### 1 Comment

KSSV on 6 Oct 2017
There is inbuilt command/ function leapyear.

Andrei Bobrov on 6 Oct 2017
Please write script - file now1.m:
out = leapyears(2000,2030)
function out = leapyears(startYear,endYear)
y = (startYear:endYear)';
x = rem(y,[4,100,400]);
out = y(x(:,1)==0 & x(:,2) | x(:,3) == 0);
end
use
>> now1
out =
2000
2004
2008
2012
2016
2020
2024
2028
>>

ES on 6 Oct 2017
Edited: ES on 6 Oct 2017
function [leapyears] = leapyears(startyear,endyear)
leapyears = [];
for iYr=startyear:endyear
if mod(iYr,4)==0 && (mod(iYr,100)~=0 || mod(iYr,400)==0)
leapyears = [leapyears;iYr];
end
end
end

Mischa Kim on 6 Oct 2017
Edited: Mischa Kim on 6 Oct 2017
Aaron, you could do something like
function leapyr = leapyears(startYear, endYear)
%UNTITLED8 Summary of this function goes here % Detailed explanation goes here
leapyr = [];
for year = startYear:endYear
if mod(year, 4) == 0 % divisible by 4?
if ~(mod(year, 100) == 0 && mod(year, 400) ~= 0)
leapyr = [leapyr,year]; % simply add leap year to vector of leap years
end
end
end
end