Matlab Lect 6
Matlab Lect 6
Week 6
IF STATEMENT
If evaluates a logical expression and
executes a group of statements based on the
value of the expression.
Syntax of If Statement
if expression
Statements
end
EXAMPLE
x = 10;
if x ~= 0
disp('Nonzero value')
end
Output:
Nonzero value
EXAMPLE
a = 100; b = 200;
if( a == 100 )
if( b == 200 )
fprintf('Value of a is 100 and b is 200\n' );
end
end
fprintf('Exact value of a is : %d\n', a );
fprintf('Exact value of b is : %d\n', b );
Output:
Value of a is 100 and b is 200 Exact
value of a is : 100 Exact value of b
is : 200
EXAMPLE
x = 78;
if x >= 90
disp('A')
end
if x >= 80
disp(‘B')
end
if x >= 70
disp(‘C')
Output:
end B
if x >= 60
disp(‘D')
end
if x <60
disp(‘F')
end
MATLAB IF-ELSE... END STATEMENT
If the first condition is not true, then we can
define other statements to run by using
the else keyword.
Syntax:
if expression
Statements
else
Statements
end
Flow Diagram of if...else...end Statement
EXAMPLE
% program to check the number is even or odd
a = randi(100,1);
if rem(a,2) == 0
disp('an even number')
else
disp('an odd number')
end
Output :
a = 15 an odd number
EXAMPLE
% Using if-else statement to determine the
largest of two number
num1 = input('Enter number 1: ');
num2 = input('Enter number 2: ');
if (num1 > num2)
disp('num1 is greater than num2')
else if (num1 < num2)
disp('num1 is less than num2')
else if (num1 == num2)
disp('num1 is equal to num2')
Output :
end Enter number 1: 15 Enter number 2:20 num1 is less than
num2
MATLAB IF-ELSEIF-ELSE...END STATEMENT