LOOPS For EE 201 C10-1 SPRING 2012
Class Learning Objectives Achieve Comprehension LOL of using Loops in programming. C10-1 SPRING 2012
Session Agenda Contact before work 5 min. For statements 70 min. C10-1 SPRING 2012
Contact before work Burning Questions C10-1 SPRING 2012
Loops A loop is a structure for repeating a calculation a number of times. Each repetition of the loop is a pass(iteration). MATLAB uses two types of explicit loops: a-for loop: when the number of passes (iterations) is known ahead of time. b-while loop : when the looping process must terminate when a specified condition is satisfied, and thus the number of passes is not known in advance. C10-1 SPRING 2012
For loops When we wish to repeat a set of instructions for a set number of times we generally use a for loop. The Syntax: for loop variable=initial value: increment value: end value statements end C10-1 SPRING 2012
Flow chart for loop variable=initial value: increment value: end value statements end Loop variable= Initial value Loop variable<=end value loop variable=loop variable+increment value T statements F end C10-1 SPRING 2012
A simple example of a for loop is T Start K <=35 X = K ^ 2 End K = K + 10 K=5 % for loop for k = 5:10:35 % compute x = k^2 end C10-1 SPRING 2012
A simple example of a for loop is 1st iteration Start K <=35 X = K ^ 2 End K = K + 10 K=5 % for loop for k = 5:10:35 % compute x = k^2 end K=5 K=15 K=5 K=5 K=15 X=25 X=25 C10-1 SPRING 2012
A simple example of a for loop is 2nd iteration Start K <=35 X = K ^ 2 End K = K + 10 K=5 % for loop for k = 5:10:35 % compute x = k^2 end K=25 K=15 K=15 K=25 X=225 X=225 C10-1 SPRING 2012
A simple example of a for loop is 3rd iteration Start K <=35 X = K ^ 2 End K = K + 10 K=5 % for loop for k = 5:10:35 % compute x = k^2 end K=35 K=25 K=25 K=35 X=625 X=625 C10-1 SPRING 2012
A simple example of a for loop is 4th iteration Start K <=35 X = K ^ 2 End K = K + 10 K=5 % for loop for k = 5:10:35 % compute x = k^2 end K=45 K=35 K=35 K=45 X=1225 X=1225 C10-1 SPRING 2012
A simple example of a for loop is 5th iteration Start K <=35 X = K ^ 2 End K = K + 10 K=5 % for loop for k = 5:10:35 % compute x = k^2 end K=45 K=45 C10-1 SPRING 2012
Trace the previous example program and fill in the table below, which shows how the program variables change over the time of the execution of the program. Iteration# k x C10-1 SPRING 2012
Iteration# k x 1 5 25 2 15 225 3 625 4 35 1225 C10-1 SPRING 2012
Example Draw a flowchart and Write a MATLAB program that finds the sum of first 50 natural numbers. C10-1 SPRING 2012
Flowchart OR C10-1 SPRING 2012
C10-1 SPRING 2012