Professional Documents
Culture Documents
(CSC209)
Lecture (11)
Loops (While and for)
Structure:
The Code Block is repeated
until the expression is false.
If it is false, the program
executes the first statement
after the end.
5
THE while LOOP
Example 1:
x = input('Enter first value: ');
while x >= 0
disp('x')
end
6
THE while LOOP
Example 2:
x = input('Enter first value: ');
while x >= 0
disp('x')
x = input('Enter second value: ');
end
k=2*x
x = 0;
y = 10;
while x < y
x=x+1
disp(x)
Pause(2)
end
8
The For Loop
THE for LOOP
Structure:
Repeats a block of statements (Body) specified
number of times.
Matlab generates an array by
evaluating this expression
column by column.
Legal Examples:
10
Example (1): THE for LOOP
>> Untdditled4
for x=0:10 0
disp(x)
1.00
end
2.00
3.00
4.00
5.00
6.00
7.00
8.00
9.00
10.00
Example (2): THE for LOOP
>> Untdditled4
for x=0:2:10 0
n=i;
2.00
disp(x)
end 4.00
6.00
8.00
10.00
Example (3): THE for LOOP
Write a MATLAB program to define the sum of the
first 25 number
sum=0;
for k=1:25
sum=sum+k;
end
disp('The total number is:')
disp(sum)
18
Practice
19
Practice: THE for LOOP
1. Write a Matlab program that finds the some of first 25
natural number.
2. Write a Matlab program that finds the some of first 25
natural number
3. (Only events).
4. Write a Matlab program that finds the some of first 25
natural number
5. (Only odds).
20
THE while LOOP
Practice:
Write a program that calculates the average,
23