You are on page 1of 26

Lecture 4

Program Flow Control

Algorithms (Flow Charts)


 An algorithm is a step-by-step solution to a given problem.
 It represents a program’s flow control.
 Flow chart can be used to des gn algor thms.
 Composed of standard box symbols.
 Outl nes solution steps to a problem and flow of program control.
 After draw ng a flowchart, programmer should convert t to Matlab commands.

Dec s on chart Repetition chart


Sequence chart (Branch ng) (Loop ng)

block1 false
condition condition
true false

block2 true
block1 block2
block

2
Example Problem: Water B ll Calculat on
PURPOSE: Wr te a Matlab program to calculate the B ll for one
customer’s water consumpt on n a month.

INPUTS
Water consumpt on amount (m3)
Un t pr ce of water (TL / m3)

OUTPUT
B ll (payment) for the month.

CALCULATION METHOD
Up to 50 m3 of water consumpt on, the b ll s calculated as usual.
If water consumpt on s more than 50 m3, then the exceed ng amount
of consumpt on s charged 30% add t onal of un t pr ce.
3

Flow Chart of Water B ll Calculat on


Beg n

Input Amount
and Un tPr ce
from keyboard

False Amount True


<= 50 ?

Bill = 50 * UnitPrice

Bill = Amount * Un tPr ce


Extra = (Amount – 50) * (1.3 * Un tPr ce)

Bill = Bill + Extra

D splay B ll
on screen

End 4
Matlab Program
% Program calculates only one customer’s bill.
% Consumption amount input should be a scalar value (non-vector).
clc; clear;

Amount = input('Enter the water consumption amount : ');


UnitPrice = input('Enter the unit price : ');

if (Amount <= 50)


Bill = Amount * UnitPrice;
else
Bill = 50 * UnitPrice;
Extra = (Amount - 50) * (1.3 * UnitPrice);
Bill = Bill + Extra;
end

Bill % Prints the result on screen

Enter the water consumption amount : 20


Screen Enter the unit price : 4
output
Bill =
80 5

Program Flow Control


Statements n Matlab
 Program flow control statements (commands) are very
mportant constructs.
 Control statements are mostly used only n M-f le scr pts,
rather than n nteract ve mode n command w ndow.
 They depend on us ng log cal express ons.

 There are two categor es of control statements.


 Dec s on statements
( f , sw tch)
 Repet t on statements
(for , wh le)

6
Log cal Express ons

 Log cal express ons are used n Dec s on statements


( f, sw tch), and Repet t on statements (for, wh le).

 A log cal express on may be any comb nat on of the follow ngs:
 Ar thmet c express ons
 Compar son operators (relat onal operators)
 Log cal var ables
 Log cal operators (and , or , not)

 When a log cal express on s evaluated by Matlab,


the result w ll be e ther true (1) or false (0).

Compar son Operators

Matlab Example of Description


operator condition (x and y are data values)

== x == y x is exactly equal to y

~= x ~= y x is not equal to y

> x>y x is greater than y

< x<y x is less than y

>= x >= y x is greater than or equal to y

<= x <= y x is less than or equal to y

8
Examples: Compar son Operators

Matlab answer Matlab answer


Example Example
(1 means True, (1 means True,
condition condition
0 means False) 0 means False)

20 == 20 1 20 > 30 0

20 ~= 20 0 20 >= 30 0

20 == 30 0 20 < 30 1

20 ~= 30 1 20 <= 30 1

Example: Compar ng An Element of Vector

>> A = [20 50 70 10 30];


 Value of A(3) s 70.
 It s compared w th 40.
>> A(3) > 40  70 > 40 cond t on s true.
ans =  Matlab returns 1 (true) as answer.
1

>> A(3) > 80  A(3) s compared w th 80.


 70 > 80 cond t on s false.
ans =  Matlab returns 0 (false) as answer.
0

10
Example: Compar ng All Elements of Vector
 Each element of A vector s compared w th scalar value 50, one-by-one.
 The Matlab answer s a log cal vector.
 In the answer vector, element locat ons that meets the cond t on are true (1) ,
others are false (0).

>> A = [20 50 70 10 30];

>> A >= 50

ans =
0 1 1 0 0


The follow ng express on s dent cal to the above express on.

>> [ 20 >= 50 50 >= 50 70 >= 50 10 >= 50 30 >= 50 ]

ans =
0 1 1 0 0

11

Example: Compar ng All Elements


of Two Vectors
 Each element of A vector s compared w th
the correspond ng element of B vector, one-by-one.
 Compar son operat ons are element-w se (element-by-element).

>> A = [20 50 70 10 30];


>> B = [20 60 50 30 20];

>> A >= B
ans =
1 0 1 0 1


The follow ng express on s the same as above.
>> [ 20 >= 20 50 >= 60 70 >= 50 10 >= 30 30 >= 20 ]

ans =
1 0 1 0 1

12
Example: Compar ng All Elements
of a Matr x w th a Scalar
 Each element of A matr x s compared w th the scalar value 25, one-by-one.
 The Matlab answer s a log cal matr x.

>> A = [20 10 40 60 ;
70 30 20 10 ]

>> A > 25
ans =
0 0 1 1
1 1 1 0

13

Example: Compar ng Vector


ar thmet c express on w th a Scalar

>> a = [2 4 6];

>> b = [3 5 6];

>> (a + b) / 2

ans =
2.5000 4.5000 6.0000

>> (a + b) / 2 >= 3

ans =
0 1 1

14
Log cal Operators
 Log cal operators (Boolean operators) are used n program flow-control
statements such as f, for.
 They can also be used to perform operat ons on log cal vectors and matr ces.

Matlab
Operator
Operator Description Pr or ty
Name
Symbol
Returns 1 for every element location that
& And is true (nonzero) in both arrays. Med um
Returns zero for all other elements.
Returns 1 for every element location that
is (nonzero) in either one or the other, or
| Or
both arrays.
Lowest
Returns zero for all other elements.
Complements each element of input array.
~ Not 1’s become 0’s. H ghest
0’s become 1’s

15

Truth Tables for Logical Operators


(AND) (OR)
Express on1 Express on1
Express on1 Express on2 & Express on1 Express on2 |
Express on2 Express on2
false false false false false false
false true false false true true
true false false true false true
true true true true true true

(NOT)
~
Express on
Express on
false true
true false

16
Examples : Log cal operators

• A and B are def ned as log cal vectors. • Test ng the log cal operators.

>> A = [true true false false] >> A & B


A = ans =
1 0 0 0
1 1 0 0

>> B = [true false true false] >> A | B


ans =
B =
1 1 1 0
1 0 1 0

>> ~ A
• Alternat ve method : ans =
Us ng the bu lt- n log cal funct on. 0 0 1 1

>> A = logical( [1 1 0 0] )
A =
1 1 0 0
17

Examples : Comb n ng Log cal and


Compar son Express ons

>> a = [2 4 6]; a < b & a == b The AND operator s


>> b = [3 5 6]; appl ed to the
correspond ng
[1 1 0] & [0 0 1] elements of two log cal
>> a < b vectors.
ans = [1 1 0]

ans = [0 0 0]
>> a == b
ans = [0 0 1]

a < b | a == b
The OR operator s
appl ed to correspond ng
[1 1 0] | [0 0 1] elements of two log cal
vectors.
ans = [1 1 1]

18
Dec s on Statements
( f , sw tch)

19

Dec s on Statements

 Sometimes a program is requ red to perform one set of


actions, if a condition is true.
 If the cond t on is false, other set of actions are performed.

 The branching or conditional action can be achieved by


the use of the " f" or "sw tch" dec s on statements.

20
f W th one statement
 There are several syntax forms of the f statement.
 The f statement should be f n shed w th end statement.

f log cal express on , s ngle statement; end

 The example below has s ngle statement syntax.


 The d sp command s wr tten on the same l ne.

f Num > 0 , d sp (‘Number s pos t ve’) ; end

True Num > 0 False


?

D splay
”Number s pos t ve”

21

f W th mult ple statements


When there are more than one statement n the true block,
we can wr te them n followed l nes unt l the end keyword.

f log cal express on


Statements to be done f true
True False
end Num > 0
?

D splay
”Number s pos t ve”
f Num > 0
d sp (‘Number s pos t ve’)
Toplam = Toplam + Num
Toplam = Toplam + Num
end

22
f W th opt onal else sect on

When the cond t on (result of log cal express on) s true,
then only the f rst part s executed.

Otherw se only the second part s executed.

f log cal express on


Statements to be done if true
else
Statements to be done if false True False
Num > 0
end ?

D splay D splay
”Number s pos t ve” ”Number s negat ve”

f Num > 0
d sp (‘Number s pos t ve')
else
d sp (‘Number s negat ve')
end

23

Nested f Statements
• There may be several else f statements, and there may or may not be an else.
• Every else clause should be closed w th an end statement.
• The else f clause does not have to to be closed w th an end.
• When wr t ng nested loops, t s a good dea to do ndentat on (spac ng from left s de).

f log cal express on1


......

else f log cal express on2


......

else f log cal express on3


......

else
...... Opt onal
last block

end
24
Example : Determ n ng the letter grade
 Wr te a Matlab program to ask user to enter a numer cal grade from keyboard.
 Program should determ ne the letter grade and d splay a message on screen.

Notu = input("Enter a numerical grade : ");

if (Notu >= 90)


disp('Letter grade is A')
else if (Notu >= 80)
disp('Letter grade is B')
Vers on1 else if (Notu >= 70)
disp('Letter grade is C')
else if (Notu >= 60)
disp('Letter grade is D')
else
disp(‘Letter grade is E')
end
end
end
end
25

Example : Determ n ng the letter grade


( Alternat ve method : Us ng else f clauses )

Vers on2
Notu = 75; % Numerical grade Notu (75) s compared w th 90.

if (Notu >= 90)


disp('A') Notu (75) s compared w th 80.
elseif (Notu >= 80)
disp('B') Notu (75) s compared w th 70.
elseif (Notu >= 70)
disp('C')
elseif (Notu >= 60) Program d splays the C letter.
Then t goes to the end.
disp('D')
(Compar ng Notu w th 60 s sk pped.)
else
disp(‘E')
end

Only one end


statement
s suff c ent.
26
Us ng a Vector n f Statement

An express on (scalar or vector) s handled by the f statement as follows.

For a scalar express on : Zero means false, non-zero means true.

For a vector or matr x express on : Hav ng at least a zero means false,
hav ng no zeros means true.

f vector express on
Statements1; % Block of true result
else
Statements2; % Block of false result
end

if 0 if [ -5 2 6] if [ -5 2 6 ; 7 0 8 ]
disp ('TRUE') disp ('TRUE') disp ('TRUE')
else else else
disp ('FALSE') disp ('FALSE') disp ('FALSE')
end end end
Result: Result: Result:
FALSE TRUE FALSE
27

Compar ng a Vector
w th a Scalar n f Statement
B = [3 5 1];

if B <= 3
disp('B n n tüm elemanları 3 veya daha küçüktür.')
else
disp('B n n elemanları 3 veya daha küçük DEĞİLDİR.')
end

 Matlab compares each element of B w th scalar value 3..


[3 <= 3 , 5 <= 3 , 1 <= 3 ] results n a log cal vector
[true, false, true]
[1 0 1]

 S nce not all values n the log cal vector are true, overall cond t on s fa led.
 The else part works and d splays the second message.

28
Compar ng Two Vectors
n f Statement
A = [8 9 6];
B = [3 5 1];

if A > B
disp('A nın tüm elemanları B n n karşı elemanından büyüktür.')
else
disp('A nın elemanları B n n karşı elemanından büyük DEĞİLDİR.')
end

 A > B cond t on compares A w th B element-by-element.


[8>3 , 9>5 , 6>1] results n a log cal vector
[true, true, true]
[1 1 1]

 S nce all values n log cal vector are true, overall cond t on s true.
 The true block works and d splays the f rst message.

29

Example: Compar ng range


cond t ons n f Statement
The program below d splays 'Outs de of range' message.

a = 200;
Invalid usage:
if (10 < a & a < 50)
disp('Within range'); 10 < a < 50
else
disp('Outside of range');
end

 Matlab f rst evaluates 10 < a, mean ng 10 < 200, wh ch results n true.


 Then evaluates a < 50, mean ng 200 < 50, wh ch results n false.
 Then appl es the AND operator, (true & false), the f nal result s false.
 Program d splays the ‘Outs de of range’ message.

30
Example : Determ n ng whether
a number s Odd or Even
 Write a Matlab program to determ ne whether a scalar nteger
number (entered by user from keyboard) s odd or even.
 Method: When a number s d v ded by 2, f the rema nder s 0,
then t s even.
 If the rema nder s 1, then t s odd.
 The mod(x, y) funct on (modulo) g ves the rema nder of x / y
ar thmet c operat on.

a = input('Bir sayı giriniz :');

if mod(a, 2) = = 0
disp('SAYI ÇİFTTİR')
else
disp('SAYI TEKTİR')
end

31

Example : Calculat ng the roots of


a second degree equat on
 Wr te a Matlab program to solve a quadrat c equat on ( ax2 + bx + c = 0 )
by us ng the formula below.
 Solv ng the equat on means calculat ng the roots.
b  b 2  4 ac
X 1,2 
2a
katsayilar = input('Enter coefficients A, B, C :');
A = katsayilar(1);
B = katsayilar(2);
C = katsayilar(3);
Discriminant = B^2 - 4*A*C; Screen output
Enter coefficients A, B, C :
if Discriminant < 0 [-2 1 4]
disp('No real roots')
elseif Discriminant == 0 Two roots found
Root1 = -B /(2*A);
disp('One root found '), Root1 Root1 =
else -1.1861
Root1 = (-B + sqrt(Discriminant ) ) /(2*A);
Root2 = (-B - sqrt(Discriminant ) ) /(2*A); Root2 =
disp('Two roots found '), Root1, Root2 1.6861
end

32
Alternat ve Solut on :
Us ng the bu lt- n roots funct on
 The follow ng s a short solut on to f nd the roots of a polynom.
 The coeff c ents are used as a polynom vector, wh ch represents a second degree
polynom al.
 The bu lt- n Matlab funct on roots s called, wh ch returns a vector conta n ng two roots.

katsayilar = input('Enter coefficients A, B, C :');

% The katsayilar vector s used as a polynom vector.


kokler = roots(katsayilar)

Enter coefficients A, B, C : [-2 1 4]


Screen
kokler =
output
1.6861
-1.1861

33

sw tch Statement
 The sw tch statement is an alternative to nested f statements.
 It allows different actions to be performed depending on an express on.
 sw tch statement should be f n shed w th end statement.

sw tch express on
case ( selector1 )
block1 case1
True
block1
case ( selector2 )
False
block2
.... case2
True
block2
....
False
case ( selector_n )
block_n
otherw se True
otherw se default
default block block
end

34
Example: sw tch Statement
 An expression in switch statement can be an integer or logical expression.
(It is often just a simple variable.)
 Selectors are set of values that expression might take.
(They can be discrete values separated by commas.)
 Blocks are the set of statements to be executed.
 The otherw se keyword (opt onal) is used if expression does not lie
in any other category.

sayi = input('Tek basamaklı pozitif bir sayı girin (0-9) : ')

switch (sayi)
case {1 , 3 , 5 , 7 , 9}
disp('Number is odd')

case {0 , 2 , 4 , 6 , 8}
disp('Number is even')

otherwise
disp('Number is out of range')
end
35

Repet t on Statements
(for , wh le)

36
Repet t on Statements

 Repet t on (loop ng, terat on) s a group of instructions computer


executes repeatedly while some condition remains true.
 In general, most of the problems can be solved n Matlab
w thout us ng loops.
 Loop ng s an alternat ve method to vector zed methods.
 Some few problems can be solved only w th loop ng.
 Loop ng methods work slower, whereas vector zed methods
work faster.

37

for Repet t on Statement


 The for statement s used as a counter-controlled repet t on.
 How many times the block will be repeated is written explicitly.
 The loop will execute for each value of the counter variable from StartValue,
until StopValue, w th ncrements of Step value.
 The for statement should be f n shed w th end statement.
 The Step value s opt onal, if it is omitted ts value s 1 as default.
 Step may be negative or positive value.

for variable = StartValue : Step : StopValue


Statemenets block (repeated) var able = StartValue
end

True
False var able >
StopValue
?

Statements block

var able = var able + Step

38
Example : Calculat ng average w th
for Repet t on
 Wr te a Matlab program to calculate average of grades n a class.
 F rstly, program asks user to enter number of students (N).
 Then, user enters a grade from keyboard one at a t me, repeat ng N t mes.

Total = 0;
N = input('Enter number of students : ');

for I = 1 : N % Count the I, until exceeding N


Grade = input('Enter a grade : ');
Total = Total + Grade;
end

Avg = Total / N

Enter number of students : 4

Enter a grade : 80
Enter a grade : 70
Screen output Enter a grade : 50
Enter a grade : 90

Avg =
72.500000
39

wh le Repet t on
 The wh le statement s used as a cond t on-controlled repet t on.
 How many t mes the block w ll be repeated s not written in advance.
 The enclosed section is repeated as long as a condition (log cal express on) is true.
 The wh le statement should be f n shed w th end statement.

wh le log cal express on


Statements block (repeated)
end

True log cal False


express on

Statements block

40
Example : Calculat ng average w th
wh le Repet t on
 Wr te a Matlab program that asks user to enter a grade repeatedly,
unt l user enters -1 as the sent nel cond t on value.
 The sent nel cond t on (a Grade that s entered as -1) causes to f n sh the loop ng.
 Sent nel value (-1) s not added to the Total, because t s not a real grade.
 The f rst Grade value s read before loop ng,
so that the Grade var able s n t al zed.

Total = 0; N = 0; Screen output


% Read the first Grade before looping.
Enter a grade (-1 to stop) : 80
Grade = input('Enter a grade (-1 to stop) : ');
Enter a grade (-1 to stop) : 70
Enter a grade (-1 to stop) : 50
while Grade ~= -1
Enter a grade (-1 to stop) : 90
Total = Total + Grade;
Enter a grade (-1 to stop) : -1
N = N + 1;
Grade = input('Enter a grade (-1 to stop) : ');
Avg =
end
72.500000
Avg = Total / N

41

Alternat ve Solut ons :


Us ng bu lt- n sum , length , mean funct ons
 We can use the bu lt- n sum, length, mean funct ons,
nstead of us ng loop ng statements such as for and wh le.

Solut on1
>> Grades = input('Enter grades as vector : ');
>> Avg = sum(Grades) / length(Grades)

Solut on2 >> Grades = input('Enter grades as vector : ');


>> Avg = mean(Grades)

Screen output
Enter grades as vector : [80 70 50 90]

Avg =
72.500000

42
Example : Us ng a vector
n for Statement

 The var able Num below takes a new data value from the g ven vector
one-at-a-t me.
 Var able Num s not a loop counter, but t takes data values from the vector.
 Count of terat ons s 4, because there are 4 data elements n the vector.

Screen output
for Num = [ 20 17 36 45 ] 20
disp(Num) 17
end 36
45

43

The break Statement



Break statement is used to escape the current loop (for or while).

Causes immediate exit from a loop statement.

Program execution continues with the first statement after the loop structure.

for I = 1 : 10
if I == 5, break, end;
% Stop rest of the loop.
Control jumps to
outs de of loop
disp(I)
end

disp('Loop is broken');

1
2
Screen
3
Output
4

Loop is broken

44
The cont nue Statement

The continue statement skips the remaining statements in a loop.

Execution proceeds with the next iteration of the loop.

Control sk ps back to
next terat on n loop

Screen Output

1
for I = 1 : 10 2
if I == 5, continue, end; 3
% Skip the commands below if, at this iteration. 4
6
disp(I) 7
end 8
9
disp('Loop is skipped at 5'); 10

Loop is skipped at 5

45

Example : Calculat ng Total of


pos t ve numbers n a vector (w th loop ng)
Write a Matlab program to calculate total of only the positive numbers in a vector.

clc; clear;

Veriler = [ -50 35 60 -35 40 ]; Screen Output

Toplam = 0; % Ini al value 35


60
for I = 1 : length(Veriler) % The I is loop counter 40

if Veriler(I) > 0 Toplam =


disp( Veriler(I) ); 135
Toplam = Toplam + Veriler(I);
end

end

Toplam % Prints the result on screen

46
Alternat ve Solut on : Cond t onal Index ng
(w thout loop ng)
Instead of us ng the for loop ng statement, we can use Cond t onal Index ng
method to calculate Total of pos t ve numbers n a vector.

>> Veriler = [-50 35 60 -35 40 ]; Numbers vector s def ned

>> Veriler > 0


ans = Log cal vector s obta ned
0 1 1 0 1 (Index locat ons of Pos t ve numbers)

>> Veriler (Veriler > 0)


Log cal vector s re-used for
ans = cond t onal ndex ng to select
35 60 40 Pos t ve numbers

>> sum ( Veriler (Veriler > 0) )


Sum of selected
ans =
Pos t ve numbers
135
47

Bu lt- n Log cal Funct ons


Matlab Examples
Descr pt on
Funct on (Funct on argument s a log cal vector)
Returns log cal true (1)
any ( [false true false false] )

f any elements (at least one)


of a vector are log cal true. ans =
1
any  When used on a matr x,
returns a row vector any ( [false false false false] )
conta n ng log cal true ans =
f any elements of each 0
column are log cal true.
 Returns log cal true (1) all ( [true true false true] )
f all elements of a vector are ans =
log cal true completely. 0

all  When used on a matr x,


returns a row vector all ( [true true true true] )
conta n ng log cal true ans =
f all elements of each column 1
are log cal true.

48
Example: Water b ll calculat on
(W th Vector nputs and Cond t onal ndex ng)

Write a Matlab program to ask user to enter Amounts as vector,
and the Unit Price as scalar.

Program should calculate the Bill for each Amount value.

Two log cal vectors are def ned, then used n the funct on any.

clc; clear;
Amounts = input('Enter water consumption amounts (as vector) : ');
UnitPrice = input('Enter the unit price (as scalar) : ');
%------------------------------------------------------
lojik_vektor1 = Amounts <= 50
if any (lojik_vektor1)
Bill (lojik_vektor1) = Amounts (lojik_vektor1) * UnitPrice;
end
%------------------------------------------------------
lojik_vektor2 = Amounts > 50
if any (lojik_vektor2 )
Extra = ( Amounts (lojik_vektor2) - 50) * (1.3 * UnitPrice);
Bill (lojik_vektor2) = (50 * UnitPrice) + Extra;
end
%------------------------------------------------------
format short g
disp('Amounts Bills') % Display title line on screen
disp( [Amounts' Bill'] ) 49

Screen output
Enter water consumption amounts (as vector) : [20 50 60]

Enter the unit price (as scalar) : 4

lojik_vektor1 =
1 1 0

lojik_vektor2 =
0 0 1

Amounts Bills
20 80
50 200
60 252

50
Alternat ve solut on
Instead of defining logical vectors and using the if and the any statements,
we can directly write the conditions between paranthesis of vectors as indexes.

clc; clear;
Amounts = input('Enter water consumption amounts (as vector) : ');
UnitPrice = input('Enter the unit price (as scalar) : ');

Bill (Amounts <= 50) = Amounts (Amounts <= 50) * UnitPrice;

Extra = ( Amounts (Amounts > 50) - 50) * (1.3 * UnitPrice);


Bill (Amounts > 50) = (50 * UnitPrice) + Extra;

format short g
disp('Amounts Bills') %Display title line on screen
disp( [Amounts' Bill'] )

51

You might also like