How can i change my code by using the mod command?

Any advice or help would be greatly appreciated.
%program dayofweek.m This program acceptes any day from this month
%(April 2017) and returns the day of the week.
N=input('Enter a date for April 2017 to display the day of the week. ')
if N==0
disp('Enter a day that does not equal zero. ')
elseif N==2
disp('Sunday')
elseif N==9
disp('Sunday')
elseif N==16
disp('Sunday')
elseif N==23
disp('Sunday')
elseif N==30
disp('Sunday')
elseif N==3
disp('Monday')
elseif N==10
disp('Monday')
elseif N==17
disp('Monday')
elseif N==24
disp('Monday')
elseif N==4
disp('Tuesday')
elseif N==11
disp('Tuesday')
elseif N==18
disp('Tuesday')
elseif N==25
disp('Tuesday')
elseif N==5
disp('Wednesday')
elseif N==12
disp('Wednesday')
elseif N==19
disp('Wednesday')
elseif N==26
disp('Wednesday')
elseif N==6
disp('Thursday')
elseif N==13
disp('Thursday')
elseif N==20
disp('Thursday')
elseif N==27
disp('Thursday')
elseif N==7
disp('Friday')
elseif N==14
disp('Friday')
elseif N==21
disp('Friday')
elseif N==28
disp('Friday')
elseif N==1
disp('Saturday')
elseif N==8
disp('Saturday')
elseif N==15
disp('Saturday')
elseif N==22
disp('Saturday')
elseif N==29
disp('Saturday')
elseif N>30
disp('The entered date does NOT exist. Please enter another date. ')
end

Risposte (3)

dpb
dpb il 7 Apr 2017
Modificato: dpb il 8 Apr 2017
After your error checking all you need is
...
days={'Saturday','Sunday','Monday','Tuesday','Wednesday','Thursday','Friday'};
disp(days{mod(N,7}+1)
This is, of course, only valid for a month that begins on a Saturday; it would be more useful to use a more general routine.
NB: Unless this is homework, look at
doc weekday % more general routine
Sure there are some other newer routines with the datetime class now, too, but haven't looked for just what might be the best in that vein...
days = {'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday'};
days(mod(N,7) + 1)

Categorie

Tag

Non è stata ancora inserito alcun tag.

Richiesto:

il 7 Apr 2017

Modificato:

dpb
il 8 Apr 2017

Community Treasure Hunt

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

Start Hunting!

Translated by