Lec 12
Lec 12
Lec 12
(CSC209)
Lecture (12)
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
Legal Examples:
11
Example (1): THE for LOOP
>> Untdditled4
for x=0:10 0
n=i;
1.00
disp(x)
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)
if (a >= 0) if (a >= 0)
y=a+1; y=a+1;
else else
y=a^2+2; y=a^2+2;
end end
disp(y) End
end disp(y)
19
END
20