Need help on this program

8 views (last 30 days)
Sri Thota
Sri Thota on 28 Dec 2021
Commented: Sri Thota on 29 Dec 2021
My code is working for all random inputs, except for valid_date(2002,2,28). Could somebody please suggest? Thank you
function valid = valid_date(year,month,day)
if ((isscalar(year) && year>0 ) && (isscalar(month) && month>0) && (isscalar(day) && day>0))
%For Leap year
if (((rem(year,4) == 0) && (rem(year,100) == 0) && (rem(year,400) == 0)) || ((rem(year,4) == 0) && (rem(year,100) ~= 0)))
valid_leap = true;
else
valid_leap = false;
end
% check for february
if(valid_leap == true && month==2 && day <=29)
valid = true;
else if(valid_leap == false && month==2 && day <=28)
valid = true;
else
valid = false;
end
% check for other months
if (month==1 || month==3 || month==5 || month==7 || month==8 || month ==10 || month==12) && (day <= 31)
valid = true;
elseif (month==4 || month==6 || month==9 || month==11) && (day <= 30)
valid = true;
else
valid = false;
end
end
else
valid = false;
end

Accepted Answer

Meg Noah
Meg Noah on 28 Dec 2021
Try something like this:
function valid = valid_date(year,month,day)
if ((isscalar(year) && year>0 ) && (isscalar(month) && month>0) && (isscalar(day) && day>0))
%For Leap year
if (((rem(year,4) == 0) && (rem(year,100) == 0) && (rem(year,400) == 0)) || ((rem(year,4) == 0) && (rem(year,100) ~= 0)))
valid_leap = true;
else
valid_leap = false;
end
% check for other months
if ismember(month,[1 3 5 7 8 10 12]) && (day <=31)
valid = true;
elseif ismember(month,[4 6 9 11]) && (day <= 30)
valid = true;
elseif (month == 2 && valid_leap == true && day <=29)
valid = true;
elseif (month == 2 && valid_leap == false && day <=28)
valid = true;
else
valid = false;
end
end
  1 Comment
Sri Thota
Sri Thota on 29 Dec 2021
Hey Meg Noah, Thanks so much for the help : ) It worked.

Sign in to comment.

More Answers (0)

Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!