cse123 - lecture 4 structured programming- loops
TRANSCRIPT
CSE123 - Lecture 4
Structured Programming-Loops
Sequential and Structured Programming
Common mistakes,
Do not use turkish letters in variable names
Do not use turkish letters and blanks in m-file names
Do not use two relational operators in one expression, divide the expression and then combine it using logical operators such as and, or or xor etc…
0<x<10 incorrect
x>0 & x<10 correct
Sequential and Structured Programming
Initialization
Calculation 1
Results
Input
Initialization
Calculation 2
Calculation 3
Initialization
Calculation 1
Results
Input
Initialization
Repeat the operation3 times…
The FOR loop
for loop_variable= start:step:finish …. Statements ….end
Statements
forloop_variable= start:step:finish
loop_variable<=finish
loop_variable>finish
Basic rules for “for” loop
• Default value for step: 1• The step can be negative • If start = finish, the loop is executed
once.• Usually NOT a good idea to change
the loop_variable inside the loop.
INCREMENTloop_variable
% program to test a for loop
for i=1:10 disp(i*0.2)end
>> testloop0.20.40.6…2.0
% program to test a for loop
for i=1:10 disp(i*0.2)end
>> testloop0.20.40.6…2.0
Example: testloop.m
% program to test a for loop
for i=1:10 disp(i)end
>> testloop123..10
% program to test a for loop
for i=1:10 disp(i)end
>> testloop123..10
>> disp(i)
10
The FOR loop
>> disp(i)
10
% program to test a for loop
for i=1:0.1:2 disp(i*5)end
>> testloop55.56..9.510
% program to test a for loop
for i=1:0.1:2 disp(i*5)end
>> testloop55.56..9.510
>> disp(i)
2
The FOR loop
Example :Assume we have series of natural numbers up to 100 and want to find the summation of these numbers.
•Use a for loop, using the loop variable as the index
•At every step of the loop, we want to add the value corresponding to the index.
Summation is done by addition of 1st elements, obtain partial result, add 2nd element, obtain partial result, etc….
Loop variable: i
Result variable: sum
% program to test a for loop
sum=0;
for i=1:100
sum=sum+i;
end
disp(sum)
disp([‘result=‘,num2str(sum)])
% program to test a for loop
sum=0;
for i=1:100
sum=sum+i;
end
disp(sum)
disp([‘result=‘,num2str(sum)])
sum=sum + next value
The FOR loop
Applications and uses of “for” loops Use loop_variable as a counter
Example :We want to calculate the …… 100 times
•Use a for loop, using the loop variable as the index of the vector.
•At every step of the loop, we want to add the value corresponding to the index.
•Operation done by taking the square root of the preceding result, 100 times
Loop variable: j
Result variable: S
% program to test a for loop
for j=1:100
end
% program to test a for loop
for j=1:100
end
S=sqrt(S)
S=pi; Initialization
S= S
. .
The FOR loop
INCREMENTloop_variable
Statements
forloop_variable= start:step:finish
IF loop_variable<=finish
IF loop_variable>finish
Add step to loop_variable
Assume 1000 values
We want to stop the loop when we obtain enough preicison in the calculation
What will happen if the precision is obtained after 10 calculations?
The FOR loop will not stop until the 1000 .
Background tests and operations
The WHILE loop
Statements
Whilelogical_expression
IF logical_expression TRUE
IF logical_expression FALSE
while logical_expression
Statements
end
Basic rules for “while” loop
• Usually necessary to create your loop_ variable or counter.
• NECESSARY to change the loop_variable inside the loop.
The WHILE loop
% program to test while loop
while i<10 i=i+1; disp(i)
end
% program to test while loop
while i<10 i=i+1; disp(i)
end
>> exloop1 12345678910 >> disp(i) 10
% program test
for i=1:10
disp(i)
end
i=0;
Example: exloop1.m
Had to create acounter
The WHILE loop
>> exloop2 9.5000 2.2513 9.0000 2.1972 8.5000 2.1401 8.0000 2.0794 7.5000 2.0149 7.0000 1.9459 6.5000 1.8718 6.0000 1.7918 5.5000 1.7047 5.0000 1.6094 4.5000 1.5041 4.0000 1.3863 3.5000 1.2528 3.0000 1.0986 2.5000 0.9163 2.0000 0.6931 1.5000 0.4055 1 0
% program to test while loop x=10; while x>1
x=x-0.5; y=log(x); disp([x,y])
end
Example: exloop2.m
The WHILE loop
>> exloop3
% BAD while loop x=1; while x>=0
x=x+0.5; y=sin(x);
end disp(‘END of program’)
Example: exloop3.m
Need to stop the script manually !!!
CTRL C
This is an Infinite loop !!!!
>>
% BAD while loop x=1; while x>=0
x=x+0.5; y=sin(x);
end disp(‘END of program’)
The WHILE loop
Example : exloop4.mCalculate the sum of manually entered numbers. Entering 0 or a negative number stops the loop and display the average.
•Need input statement:
•Use the length of A in the logical_expression
•Inside the loop:•Increment a counter to count how many value we entered
•Add the value A to the sum S
A>0
% program to test a while loop
while
endN=i-1disp(S/N)
% program to test a while loop
while
endN=i-1disp(S/N)
Use while loop when the number of operation is unknown
variable: A
S=S+A
i=i+1
>> testloopValue for A:2Value for A:2Value for A:2Value for A:2Value for A:0 2
>> testloopValue for A:2Value for A:2Value for A:2Value for A:2Value for A:0 2
A=input('Value for A:');
A>0
i=i+1; S=S+A;
A=pi;S=0;i=0;
>> testloopValue for A:1Value for A:5Value for A:8Value for A:0 4.6667
>> testloopValue for A:1Value for A:5Value for A:8Value for A:0 4.6667
The WHILE loop
Example 5:Series convergence: π2/6
Want to see how many terms you need to obtain an error of 3x10-6.
% Convergence script
while
end
disp(['N=',num2str(i)])
% Convergence script
while
end
disp(['N=',num2str(i)])
Use logical_expression for convergence limit
N
1ii12
>> Testloop
N=333333
>> Testloop
N=333333
•Need to define and use an error variable.•Need to be part of the logical expression•Need to be updated during loop
•At every step of the loop, we want to•Verify if test is true
•Increment counter
•Add the new term to the sum
err
S=S+ 1/i^2
i=i+1
err>3e-6
err=abs(S-pi^2/6);
i=i+1;S=S+ 1/i^2;
S=0; i=0;err=10;
(err>3e-6)
The WHILE loop
% Convergence script
S=0; i=0;err=10;
while err>3e-6 i=i+1; S=S+ 1/i^2; err=abs(S-pi^2/6); A(i)=err;end
disp(['N=',num2str(i)])
% Convergence script
S=0; i=0;err=10;
while err>3e-6 i=i+1; S=S+ 1/i^2; err=abs(S-pi^2/6); A(i)=err;end
disp(['N=',num2str(i)])
Use logical_expression for convergence limit
>> Testloop
N=333333
>> Testloop
N=333333
Nested loops and combination
Example: exloop6.mCalculate the sum of factorials up to 20
•Need a for loop for sums
•Need a for loop for factorials
•Calculate the factorial of element j
•Do the sum on all elements
% program to test nested loops
S=0; for i=1:20 F=1; for j=1:i F=F*j; end S=S+F end disp(S)
% program to test nested loops
S=0; for i=1:20 F=1; for j=1:i F=F*j; end S=S+F end disp(S)
Using nested loops
S=S+F
j
i
!20....!4!3!2!1
F=F*j
The “BREAK” statement
BREAK
•Break terminates the execution of a for or while loop. 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 that follows the end of that loop.
% BAD while loop
x=1;
while x>=0
x=x+0.5; y=sin(x);
end
if x>10000break
end
The “CONTINUE” statement
CONTINUE
• Continue passes control to the next iteration of the for or while loop in which it appears, skipping any remaining statements in the body of the loop.
% Problem of division by 0
x=1;
for i= -10:10
y=1/x;
end
if x==0continue
end
The FOR loop
Example :Write a Matlab script tp calculate following expression for an enetered x value
x1
1
11
11
11
The FOR loop
Example :Write a Matlab script tp calculate mean and standard deviation of an input data set containing an arbitrary number of input values. Check to see if there is enough input data (N>1) to eliminate division by zero.
N
iixN
x1
1
)1(
)(1 1
22
NN
xxNs
N
i
N
ii i
Break
Example :Run the following loops and report the result
for ii=1:3
for jj=1:3
if jj==3
break;
end
Product=ii*jj;
fprintf(‘%d * %d = %d \n’,ii,jj,product);
end
fprintf(‘end of inner loop\n’);
end
fprintf(‘end of outer loop\n’);
1 * 1 = 1
1 * 2 = 2
end of inner loop
2 * 1 = 2
2 * 2 = 4
end of inner loop
3 * 1 = 3
3 * 2 = 6
end of inner loop
end of outer loop