MATLAB Answers

Can anyone point out the mistake in this program? It's regarding writing a function to check if the entered date is valid or not.

19 views (last 30 days)
Sanjeeb Bharali
Sanjeeb Bharali on 18 Feb 2019
Edited: Jan on 30 Mar 2019
Here is the code that I have written, but it gives wrong answers for date such as 31st April 2018 (2018,4,31). Ideally the program should give me logical 0, however, it gives me logic 1.
function [valid]=valid_date(year, month, day)
if isscalar(year) && year>0 && year~=0 && isscalar(month) && month>0 && month~=0 && isscalar(day) && day>0 && ar
if mod(year,4) == 0 && mod(year, 100)~= 0 || mod(year,400)==0 && month==2 && days<=29
%for february
valid=true;
else
valid=false;
end
%for rest of the months
if month==4 || month==6 || month==9 || month==11 && day<=30
valid=true;
elseif month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month== 12 && day<=31
valid=true;
else
valid=false;
end
%not a leap year
if month==2 && day>28
valid=false;
end
%rest of the months
if month==4 || month==6 || month==9 || month==11 && day<=30
valid=true;
elseif month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month== 12 && day<=31
valid=true;
else
valid=false;
end
else
valid=false;
end

Answers (1)

praveen
praveen on 19 Feb 2019
it has to be
if (month==4 || month==6 || month==9 || month==11) && day<=30
valid=true;
elseif (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month== 12) && day<=31
valid=true;
else
valid=false;
end
Use Parentheses generously. It is a good idea to use parentheses to explicitly specify the intended precedence of statements containing combinations of & and |

  1 Comment

Jan
Jan on 29 Mar 2019
There are much more errors in the code. E.g. the first test fails, because the if condition ends with the meaningless "&& ar".

Sign in to comment.

Sign in to answer this question.

Products


Release

R2018b