Professional Documents
Culture Documents
Flow-Chart and If Statement
Flow-Chart and If Statement
Mahmood H. Majeed
April 13, 2016
1 Flow Chart
• For start and end use • For conditional use:
Solution:
Flow-chart design: Program design
Start function y=name(x)
if x==0
y=x^3+5*x-2
input x else
y=x^2+5
end
No
x=0 y = x2 + 5 end
Yes
y = x3 + 5x − 2
print y print y
end
1
2 If Statements
IF statements use relational or logical operations to determine what steps to perform
in the solution of a problem. The relational operators in MATLAB
R
for comparing
two matrices of equal size are shown in Table (1).
• Simple if statement
• Nested if statement
• If-else statement
• If-elseif-...-else statement
*****************************************************
if logical expression
statement
end
y = x2 + 2x − 5
Solution:
function y=name(x)
if x==-1
y=x^2+2*x+5
end
2
• The general form of a nested if statement is:
if logical expression 1
statement group 1
if logical expression 2
statement group 2
end
end
Solution:
function z=name(x)
if x>5
y=2*x+6
if y<=2
z=y^2+3*x
end
end
if logical expression 1
statement group 1
else
statement group 2
end
if logical expression 1
statement group 1
elseif logical expression 2
statement group 2
elseif logical expression 3
statement group 3
..
.
else
statement group n
end
ax2 + bx + c = 0
Solution:
function [x1,x2]=name(a,b,c)
D=b^2-4*a*c;
if D>0
x1=(-b+sqrt(D))/(2*a)
3
x2=(-b-sqrt(D))/(2*a)
elseif D=0
x1=-b/(2*a)
x2=x1
else
disp(’The root is complex’)
end
Solution:
function [y]=name(x)
if x==2 | x==3
y=sin(pi*x/2)+cos(pi*x)
end
Solution: H.W.