Download presentation
Presentation is loading. Please wait.
Published byCecily Webb Modified over 9 years ago
1
1 Conditional Statements + Loops ผศ. ดร. อนันต์ ผลเพิ่ม Anan Phonphoem http://www.cpe.ku.ac.th/~anan anan@cpe.ku.ac.th
2
2 Overview Condition statement If If-else If-elseif Nested Logic Loops for while
3
3 Flowcharts Graphical representation of algorithm Terminator Process Input/output Decision Connector Flow line
4
4 Flowchart example Start Read width Read length Total = width + length If total ~= 0 show total End No Yes
5
5 If Statement (In real life) If I have free time, I will go to visit my friend. (period)
6
6 If Statement (In MATLAB) If logical expression statements end condition False True Statement
7
7 If Statement (Example) If a <= 30 total = 2*a end a <= 30 False True total = 2*a
8
8 If-else Statement (In real life) If I have free time, I will go to visit my friend else, I will send an email to her. (period)
9
9 If-else Statement (In MATLAB) If logical expression statement group 1 else statement group 2 end condition False True Statement2Statement1
10
10 If-else Statement (Example) a <= 30 False True total = a+10total = 2*a If a <= 30 total = 2*a else total = a + 10 end
11
11 Nested Logic - I (In real life) If I have free time, I will go to visit my friend If she is not there I will leave a message. (period)
12
12 Nested Logic – I (In MATLAB) If logical expression 1 statement group 1 If logical expression 2 Statement group 2 end condition1 False True condition2 False True Statement2 Statement1
13
13 Nested Logic – I (Example) If a <= 30 c = a + 10 If c <= 12 c = 0 end a <= 30 False True c <= 12 False True c = 0 c = a + 10
14
14 Nested Logic – II (In real life) If I have free time, I will go to visit my friend elseif I can access computer I will send her an email else I will leave her a note. (period)
15
15 Nested Logic – II (In MATLAB) condition1 False True Statement1 condition2 FalseTrue Statement3Statement2 If logical expression 1 statement group 1 elseif logical expression 2 statement group 2 else statement group 3 end
16
16 Nested Logic – II (Example) a <= 30 False True c = a * 2 c >= 20 FalseTrue d = 0 d = c If a <= 30 c = a * 2 elseif c >= 20 d = c else d = 0 end
17
17 Loops Repeating a calculation for a number of times Each repetition of the loop is a pass Two types of loops (In MATLAB) for loop while loop
18
18 for loops for loop variable = m:s:n statements end Variable > n True False Increment variable by s Set loop variable = m Statements
19
19 for loops (Example) for a = 1:2:10 total = total + a end a > 10 True False a = a + 2 a = 1 total = total +a
20
20 for loops for loop variable = m:s:n statements end Note: for a = 10:-2:0 c = a * 2 end for a = 1:100 c = a * 2 end for a = 10:2:5 c = a * 2 end for a = 2:2 c = a * 2 end for a = 2:1.5:20 c = a * 2 end
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.