Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
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
if choice > 0
disp('You must be a
elseif choice < 0
disp('You must be a
else
disp('You must be a
end
a number: ');
very positive person.');
very negative person.');
neutral person.');
TDDD34 - Lecture 2
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
3/7
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
The
The
The
control
control
control
control
variable
variable
variable
variable
is
is
is
is
1
2
3
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
I
I
I
I
I
I
I
I
I
I
I
I
love
love
love
love
love
love
love
love
love
love
love
love
love
you!
you!
you!
you!
you!
you!
you!
you!
you!
you!
you!
you!
you!
(Continues indefinitely)
TDDD34 - Lecture 2
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...
6/7
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
+--+--+--+
| | | |
+--+--+--+
| | | |
+--+--+--+
| | | |
+--+--+--+