210 likes | 389 Views
Conditional Statements + Loops. ผศ.ดร.อนันต์ ผลเพิ่ม Anan Phonphoem http://www.cpe.ku.ac.th/~anan anan@cpe.ku.ac.th. Overview. Condition statement If If-else If-elseif Nested Logic Loops for while. Terminator. Process. Input/output. Decision. Connector. Flow line. Flowcharts.
E N D
Conditional Statements + Loops ผศ.ดร.อนันต์ ผลเพิ่ม Anan Phonphoem http://www.cpe.ku.ac.th/~anan anan@cpe.ku.ac.th
Overview • Condition statement • If • If-else • If-elseif • Nested Logic • Loops • for • while
Terminator Process Input/output Decision Connector Flow line Flowcharts • Graphical representation of algorithm
Flowchart example Start Read width Read length Total = width + length If total ~= 0 No Yes show total End
If I have free time, I will go to visit my friend . (period) If Statement(In real life)
If logical expression statements end condition False True Statement If Statement (In MATLAB)
a <= 30 False True total = 2*a If a <= 30 total = 2*a end If Statement(Example)
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)
condition True False Statement1 Statement2 If-else Statement (In MATLAB) If logical expression statement group 1 else statement group 2 end
a <= 30 True False total = 2*a total = a+10 If-else Statement (Example) If a <= 30 total = 2*a else total = a + 10 end
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)
False condition1 True Statement1 False condition2 True Statement2 Nested Logic – I (In MATLAB) If logical expression 1 statement group 1 If logical expression 2 Statement group 2 end end
False a <= 30 True c = a + 10 False c <= 12 True c = 0 Nested Logic – I (Example) If a <= 30 c = a + 10 If c <= 12 c = 0 end end
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)
condition1 False True condition2 True False Statement1 Statement2 Statement3 Nested Logic – II (In MATLAB) If logical expression 1 statement group 1 elseif logical expression 2 statement group 2 else statement group 3 end
a <= 30 False True c >= 20 True False c = a * 2 d = c d = 0 Nested Logic – II (Example) If a <= 30 c = a * 2 elseif c >= 20 d = c else d = 0 end
Loops • Repeating a calculation for a number of times • Each repetition of the loop is a pass • Two types of loops (In MATLAB) • forloop • while loop
Set loop variable = m for loop variable = m:s:n statements end True Variable > n False Statements Increment variable by s for loops
for a = 1:2:10 total = total + a end for loops (Example) a = 1 True a > 10 False total = total +a a = a + 2
for loop variable = m:s:n statements end for loops 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