Lecture15.Switch-case-example-and-While-loop

advertisement
Introduction to
Programming in
MATLAB
Intro. MATLAB Peer Instruction Lecture Slides by Dr. Cynthia Lee, UCSD is licensed under
a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
Based on a work at www.peerinstruction4cs.org.
1
SWITCH-CASE
2
Switch-Case Programming
• Goal: we want to write a function that
converts month numbers to the
corresponding month names
– MonthName(12) returns ‘December’
– MonthName(3) returns ‘March’
– Etc.
• Input argument is the number, we will return
a string of the name.
3
FUNCTION DEFINITION LINE:
[outputs]
function
=
function name
(arguments)
function [name] = MonthName(number)
_________________
We start by writing the Function Definition Line,
which has been done for you. What should go on
the blank line to begin the body of our function?
a) case name
b) switch name
c) case number
d) switch number
e) Other/error
4
function [name] = MonthName(number)
_________________
_________________
What should go on the blank line to continue
our code?
a)case 1
b)case name
c)case ‘January’
d)case number
e) Other/error
5
function [name] = MonthName(number)
_________________
_________________
_________________
What should go on the blank line to continue
our code?
a)display(‘January’)
b)display(‘1’)
c)name = ‘January’
d)number = 1
e) Other/error
6
function [name] = MonthName(number)
switch number
case 1
name = ‘January’;
case 2
name = ‘February’;
case 3
name = ‘March’;
…several more cases here!…
case 12
name = ‘December’;
otherwise
name = ‘’;
end
end
7
while loops while loops while loops while loops while loops
BACK TO WHILE LOOPS
8
How many times does this loop print
“hi”?
a) 0
b) 6
c) 7
d) 8
e) Other
i=1;
while i<=7
display(‘hi’)
end
9
How many of these print ‘hi’ seven
times?
for i = 0:7
display('hi')
end
for i = 1:7
display('hi')
end
a)
b)
c)
d)
e)
0
1
2
3
4
i=1;
while i<=7
display(‘hi’)
i = i + 1;
end
i=0;
while i<7
display(‘hi’)
i = i + 1;
end
Can you write another loop, different from all these, that
prints ‘hi’ seven times?
10
Download