Loop and Conditionaling Program
Loop and Conditionaling Program
Loop and Conditionaling Program
Theory:
1. MATLAB – Conditional Statements
Conditional statements are something that is very basic and important for every programmer. There will
be some situations where a program or a particular block has to be executed only when a specific
condition is True. These conditional statements will be very handy and fruitful in such situations. These
conditional statements work as same as in other languages. However, syntax varies from language to
language. The following are the conditional statements that we can use in MATLAB.
if-end
if-else-end
nested-if-end
if-elseif-elseif-else-end
switch case
nested switch case
Syntax:
if (condition)
% statement(s) will execute
% if the boolean expression is true
<statements>
end
Example:
Output:
Syntax:
if (condition)
% statement(s) will execute
% if the boolean expression is true
<statement(s)>
else
<statement(s)>
% statement(s) will execute
% if the boolean expression is false
end
Example 1:
Output:
Example 2: You can also chain if-else-end statements with more than one condition.
Output:
The number is less than 30
iii. Nested if-end Statement: There comes some situations where multiple conditions have to be
satisfied to execute a block of code then we use nested if-end statements. This is nothing but
another if condition(s) inside an if condition.
Syntax:
if (condition)
% Executes when the boolean expression 1 is true
if (condition)
% Executes when the boolean expression 2 is true
end
end
Example:
Output:
iv. if-elseif-elseif-else-end: An if statement can be followed by one (or more) optional elseif and an else
statement, which is very useful to test various conditions.
Syntax:
if (condition)
% Executes when the expression 1 is true
<statement(s)>
elseif (condition)
% Executes when the boolean expression 2 is true
<statement(s)>
elseif (condition)
% Executes when the boolean expression 3 is true
<statement(s)>
else
% executes when none of the above conditions is true
<statement(s)>
end
Example:
Output:
v. Switch case: A switch block is familiar to if-elif-else-end statements. It works as same as in other
languages except for syntax. But there are a few key differences between them. A switch block
conditionally executes one set of statements from several choices. Each choice is covered by a case
statement. A switch expression can be any of the following.
Numbers
Characters
Strings
Objects
Here comparison of string expressions and case expressions is case-sensitive. Every character of a switch
string expression must be matched with the case string expression.
Syntax:
switch (condition)
case condition
<statements>
case (condition)
<statements>
…
…
otherwise
<statements>
end
Example 1:
grade = 'A';
switch(grade)
case 'A'
fprintf('Excellent!\n' );
case 'B'
fprintf('Well done\n' );
case 'C'
fprintf('Good\n' );
case 'D'
fprintf('You passed\n' );
case 'F'
fprintf('Better try again\n' );
otherwise
fprintf('Invalid grade\n' );
end
Output:
Excellent!
Example 2:
Output:
Not Matched!
Example 3:
Output:
Normal Year!
vi. Nested Switch Case: This is similar to nested if statements. We can use the switch as a part of the
statement inside a switch. Even if the inner and outer switch case constants contain common values,
no conflicts will arise.
Syntax:
switch (condition)
case (condition)
<statements>
switch (condition)
case (condition)
<statements>
…..
end
case (condition)
<statements>
end
Example: This example explains how MATLAB uses the nested switch case and string comparison.
Output:
Note:
Unlike other programming languages, we don’t need to use break statements in switch cases.
Unlike other programming languages, we don’t use any kind of parentheses (i.e., (),{},: ) while writing
conditions in conditional statements(i.e., if, nested if, etc). We do use an end statement to end a
conditional statement.
While Loop
The while loop repeatedly executes statements while a specified condition is true.
The syntax of a while loop in MATLAB is as following:
while <expression>
<statements>
end
The while loop repeatedly executes a program statement(s) as long as the expression remains
true.
An expression is true when the result is nonempty and contains all nonzero elements (logical or
real
numeric). Otherwise, the expression is false.
Example
a = 10;
% while loop execution
while( a < 20 )
fprintf('value of a: %d\n', a);
a = a + 1;
end
When the code above is executed, the result will be:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
For loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times.
The syntax of a for loop in MATLAB is as following:
for index = values
<program statements>
...
end
values can be one of the following forms:
initval:endval --- increments the index variable from initval to endval by 1, and repeats
execution
of program statements until index is greater than endval.
Initval:step:endval --- increments index by the value step on each iteration, or decrements
when step is
negative.
valArray --- creates a column vector index from subsequent columns of array valArray on each
iteration.
For example, on the first iteration, index = valArray(:,1). The loop executes for a maximum of n
times, where n is the number of columns of valArray, given by numel(valArray, 1, :). The input
valArray can be of any MATLAB data type, including a string, cell array, or struct.
Example
for a = 10:20
fprintf('value of a: %d\n', a);
end
When the code above is executed, the result will be:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20
for a = 1.0: -0.1: 0.0
disp(a)
end
When the code above is executed, the result is:
1
9/10
4/5
7/10
3/5
1/2
2/5
3/10
1/5
1/10
0
for a = [24,18,17,23,28]
disp(a)
end
When the code above is executed, the result will be:
24
18
17
23
28
Example
We can use a nested for loop to display all the prime numbers from 1 to 100.
for i=2:100
for j=2:100
if(~mod(i,j))
break; % if factor found, not prime
end
end
if(j > (i/j))
fprintf('%d is prime\n', i);
end
end
When the code above is executed, the result is:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Break statement:
The break statement terminates execution of for or while loops. Statements in the loop that
appear after the break statement are not executed.
In nested loops, break exits only from the loop in which it occurs.
Control passes to the statement following the end of that loop.
Example
a = 10;
% while loop execution
while (a < 20 )
fprintf('value of a: %d\n', a);
a = a+1;
if( a > 15)
% terminate the loop using break statement
break;
end
end
When the code above is executed, the result is:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Continue Statement
The continue statement is used for passing control to thenext
iteration of a for or while loop.
The continue statement in MATLAB works somewhat like the break
statement. Instead of forcing termination, however, 'continue'
forces the next iteration of the loop to take place, skipping any
code in between.
Example
a = 10;
%while loop execution
while a < 20
if a == 15
% skip the iteration
a = a + 1;
continue;
end
fprintf('value of a: %d\n', a);
a = a + 1;
end
When the code above got executed, the result is:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Test Your Understanding
1. factorial for numbers using a nested loop structure
2. Write a program that takes user input as a year and determines whether or not the year
is a leap year and displays the text as output: “It is a Leap Year” or “It is not a Leap Year”
3. Write a m-file program using conditional statements to evaluate y for x=−3, x=4, and
x=10. The function y is defined as: y =ex+1 for x<−2, y=2+cos(πx) for −2≤x<6, and
y=10(x−5) +1 for x≥6 Check the results by hand.
4. Write a program that uses the switch-case structure to count the number of days in a
year up to a given date, given the year, the month, and the day of the month as user
inputs.
5. Use a while loop to determine how many terms in the series 2k-1, k=1,2,3… are required
for the sum of the terms to exceed 2000 and also display the sum for the resultant
number of terms.