Loop and Conditionaling Program

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Aim: Loop & Conditional Programming

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

i. If-End Statement: An if-end statement is the simplest decision-making statement. It decides


whether a particular block of code has to be executed or not, based on the given boolean condition.
Only when the given condition is true, it execute the statements inside the block otherwise not.

 Syntax:

if (condition)
% statement(s) will execute
% if the boolean expression is true
<statements>
end

 Example:

% MATLAB program to illustrate


% if-end statement
number = 28;
if number>10
fprintf('The number is greater than 10.');
end

 Output:

The number is greater than 10.


ii. if-else-end statement: In conditional if Statement, the additional block of code is merged as another
statement, which is performed when if the condition is false; else condition won’t be executed when
if the condition is True.

 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:

% MATLAB program to illustrate


% if-else-end statement
number = 28;
if number<10
fprintf('The number is greater than 10');
else
fprintf('The number is not less than 10');
end

 Output:

The number is not less than 10

 Example 2: You can also chain if-else-end statements with more than one condition.

% MATLAB program to illustrate


% if-else chaining
number = 28;
if number<10
fprintf('The number is less than 10\n');
else
if number<20
fprintf('The number is less than 20\n');
else
fprintf('The number is less than 30\n');
end
end

 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:

% MATLAB program to illustrate


% Nested if-end statements
number = 2;
if number<10
fprintf('The number is less than 10\n');
% Executes when then above if
% condition is true
if number<5
fprintf('Also, The number is less than 5');
end
end

 Output:

The number is less than 10


Also, The number is less than 5

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:

% MATLAB program to illustrate


% if-elseif-else-end statement
number = 28;
if number<10
fprintf('The number is less than 10\n');
elseif number<20
fprintf('The number is less than 20\n');
elseif number<30
fprintf('The number is less than 30\n');
else
fprintf('The number is less than 40\n');
end

 Output:

The number is less than 30

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:

% MATLAB program to illustrate


% String evaluation while using
% switch case
% First letter of the name was
% given small letter intentionally
name = 'prashant'
switch(name)
case 'Prashant'
fprintf('Hello from %s',name);
otherwise
fprintf('Not Matched!');
end

 Output:

Not Matched!
 Example 3:

% MATLAB program to illustrate


% switch case
days = 28;
switch(days)
case 28
fprintf('Normal Year!\n' );
otherwise
fprintf('Leap Year\n' );
end

 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.

% MATLAB program to illustrate


% nested switch case
days = 29;
month = 'February'
switch(days)
case 29
fprintf('This Year is ' );
switch month
case 'february'
fprintf('Leap Year!\n' );
otherwise
fprintf('Not Leap Year!\n' );
end
end

 Output:

This Year is Not Leap Year!

 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.

Use semi-colons(;) wherever necessary to avoid unwanted outputs.

2. Loop Types in MATLAB


There may be a situation when you need to execute a block of code several times. In general,
statements are executed sequentially. The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. The
drawing shows the general form of a loop statement for most programming languages.
Matlab provides various types of loops to handle looping requirements including: while loops,
for loops, and nested loops. If you are trying to declare or write your own loops, you need to
make sure that the loops are written as scripts and not directly in the Command Window.
To start a new script, locate the button in the upper left corner of the window labeled New
Script.

 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

 The Nested Loops


Matlab also allows to use one loop inside another loop. The syntax for a nested for loop
statement in MATLAB is as follows:
for m = 1:j
for n = 1:k
<statements>;
end
end
The syntax for a nested while loop statement in MATLAB is as follows:
while <expression1>
while <expression2>
<statements>
end
end

 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

 Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. The scope defines
where the variables can be valid in Matlab, typically a scope within a loop body is from the
beginning of conditional code to the end of conditional code. It tells Matlab what to do when
the conditional code fails in the loop. Matlab supports both break statement and continue
statement.

 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.

You might also like