You are on page 1of 4

Conditional Statements:

Loops:

Expt.No.

Conditional Statements and Loops

Date:
Aim:
To know and understand the basic Conditional Statements and Loops in Matlab tool.
Softwares Required:
Matlab R2015a
Hardware Required:
A personnel Computer.
Procedures:
1.
2.
3.
4.

Open matlab File.


Type the program in the editor window.
Save the file with .m Extension and run the program.
Verify the output in the command Window.

Theory:
Conditional Statements
Relational and logical operators can be used to test conditions in if statements. The syntax of
the simplest form of an if statement is:
if condition
Do something
end;

The syntax of an if statement can be expanded so that if the condition is not true something
else is done instead:
if condition
Do something
else
Do something else
end;

Exercises:

1. Write a program to display first ten prime numbers using loop operators.

2. Write a program to display square of numbers from 1 to 10

3. Write a program to display the numbers from 10 to 1

4. Write a program to plot wanted to draw y = x2 where x varies between 1


and 5.

5. Write a program to plot

The if statement can be further expanded by the inclusion of one or more elseif
sections:

if condition
Do something
elseif another condition
Do a different thing
elseif yet another condition
Do a different thing
else
Do something else
end;
The syntax for switch statements can be explained as
switch expression
case <expression>
<list of commands>
:
case <expression>
<list of commands>
otherwise
<list of commands>
end
LOOPS
While Loops
While statements repeatedly execute a piece of code while a given condition is
true. The syntax of a
while statement is:
while condition
do something
end

For Loops
For statements repetitively execute a piece of code a given number of times. The syntax of a
for
statement is:
for counter = start:step:stop
do something
end

This loop works by setting counter = start, doing something, adding step to counter, doing
something, adding step to counter, etc until counter reaches (or passes) stop. Remember that
if the step is not specified it is assumed to be 1.

Result:

You might also like