TDDD34 - Lecture 2 1/7 Conditional Programming The if-statement: if condition statements end Example 1: choice = input('Enter a number: '); some_text = 'wrong'; if choice == 42 some_text = 'right'; end disp(['You guessed the ', some_text, ' number!']); Else: if condition statements else statements end
TDDD34 - Lecture 2 2/7 Example 1 (using else): choice = input('Enter a number: '); if choice == 42 some_text = 'right'; else some_text = 'wrong'; end disp(['You guessed the ', some_text, ' number!']); Elseif: if condition1 statements elseif condition2 statements end Note: You can have many elseifs! Else and Elseif can be used together: choice = input('Enter a number: '); if choice > 0 disp('You must be a very positive person.'); elseif choice < 0 disp('You must be a very negative person.'); else disp('You must be a neutral person.'); end
TDDD34 - Lecture 2 3/7 The Switch-statement: switch expression case value statements case value statements case {value, value} statements otherwise statements end Example choice = input('Enter a number: '); switch choice case {1 , 9 , 42 , 111} disp('That is one of my favorite numbers!'); case {-1 , 13 , 88} disp('That is a number I do not like!'); otherwise disp('I am indifferent to that number...'); end
TDDD34 - Lecture 2 4/7 The for loop: for control_variable = interval statements end Example: for i = 1:4 disp(['The control variable is ', num2str(i)]); end The output will be : The control variable is 1 The control variable is 2 The control variable is 3 The control variable is 4
TDDD34 - Lecture 2 5/7 The while loop while condition statements end Example: while true disp('I love you!'); end The output is: I love you! I love you! I love you! I love you! I love you! I love you! I love you! I love you! I love you! I love you! I love you! I love you! I love you! (Continues indefinitely)
TDDD34 - Lecture 2 6/7 Break: while true statements if condition break; end end Continue: while true if condition continue; end statements end Advice: Avoid break and continue if you can...
TDDD34 - Lecture 2 7/7 Create a program that draws a grid (with characters, so called ASCII-art). The size of the figure depends on a integer entered by the user. Solve it by using loops. Here are some examples of what the program should do when executed: example 1: Enter a number: 1 +--+ | | +--+ example 2: Enter a number: 2 +--+--+ | | | +--+--+ | | | +--+--+ example 3: Enter a number: 3 +--+--+--+ | | | | +--+--+--+ | | | | +--+--+--+ | | | | +--+--+--+
Recommend
More recommend