CSE123 - Lecture 4 Structured Programming- Loops.

Slides:



Advertisements
Similar presentations
CMPS 1371 Introduction to Computing for Engineers
Advertisements

CS0004: Introduction to Programming Repetition – Do Loops.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Repeating Actions While and For Loops
Chapter 4 Repetitive Execution. 2 Types of Repetition There are two basic types of repetition: 1) Repetition controlled by a counter; The body of the.
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 5: Control Structures II (Repetition)
Loops – While, Do, For Repetition Statements Introduction to Arrays
CHAPTER 6 REPETITIVE EXECUTION 6.1 Introduction A repetition structure or loop makes possible the repeated execution of one or more statements called the.
Lecture 12 Another loop for repetition The while loop construct © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Loops are MATLAB constructs that permit us to execute a sequence of statements more than once. There are two basic forms of loop constructs: i. while.
Fundamentals of Python: From First Programs Through Data Structures
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Fundamentals of Python: First Programs
MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014
Programming Logic and Design Fifth Edition, Comprehensive
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Looping II (for statement). CSCE 1062 Outline  for statement  Nested loops  Compound assignment operators  Increment and decrement operators.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 6 Looping.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
PROBLEM SOLVING WITH LOOPS Chapter 7. Concept of Repetition Structure Logic It is a computer task, that is used for Repeating a series of instructions.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
Chapter 5: Control Structures: Iteration Visual Basic.NET Programming: From Problem Analysis to Program Design.
Matlab Programming for Engineers
Digital Image Processing Lecture 6: Introduction to M- function Programming.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Decision Making and Branching (cont.)
Repetition Repetition allows you to repeat an operation or a series of operations many times. This is called looping and is one of the basic structured.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Tutorial 9 Iteration. Reminder Assignment 8 is due Wednesday.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
1 Looping Chapter 6 2 Getting Looped in C++ Using flags to control a while statement Trapping for valid input Ending a loop with End Of File condition.
Computer Programming -1-
REPETITION CONTROL STRUCTURE
Introduction To Repetition The for loop
Programming Logic and Design Fourth Edition, Comprehensive
Chapter 4 - Program Control
JavaScript: Control Statements.
JavaScript: Control Statements I
Topics Introduction to Repetition Structures
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
Chapter 13 Control Structures
Iteration with While You can say that again.
Control Structure Senior Lecturer
Outline Altering flow of control Boolean expressions
Iteration: Beyond the Basic PERFORM
Program Control Topics While loop For loop Switch statement
2.6 The if/else Selection Structure
Topics Introduction to Repetition Structures
Repetition Statements
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
REPETITION Why Repetition?
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation 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 operation 3 times…

The FOR loop for loop_variable= start:step:finish …. Statements …. end Statements for loop_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. INCREMENT loop_variable

% program to test a for loop for i=1:10 disp(i*0.2) end >> testloop … 2.0 % program to test a for loop for i=1:10 disp(i*0.2) end >> testloop … 2.0 Example: testloop.m % program to test a for loop for i=1:10 disp(i) end >> testloop % program to test a for loop for i=1:10 disp(i) end >> testloop >> 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 >> testloop % program to test a for loop for i=1:0.1:2 disp(i*5) end >> testloop >> 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 1 st elements, obtain partial result, add 2 nd 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 usage 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=

The FOR loop INCREMENT loop_variable Statements for loop_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 Background tests and operations

The WHILE loop Statements While logical_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 >> exloop >> disp(i) 10 % program test for i=1:10 disp(i) end i=0; Example: exloop1.m Had to create a counter

The WHILE loop >> exloop % 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.m Calculate 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 end N=i-1 disp(S/N) % program to test a while loop while end N=i-1 disp(S/N) Use while loop when the number of operation is unknown variable: A S=S+A i=i+1 >> testloop Value for A:2 Value for A:0 2 >> testloop Value for A:2 Value for A:0 2 A=input('Value for A:'); A>0 i=i+1; S=S+A; A=pi; S=0; i=0; >> testloop Value for A:1 Value for A:5 Value for A:8 Value for A: >> testloop Value for A:1 Value for A:5 Value for A:8 Value for A:

The WHILE loop Example 5: Series convergence: π 2 /6 Want to see how many terms you need to obtain an error of 3x % Convergence script while end disp(['N=',num2str(i)]) % Convergence script while end disp(['N=',num2str(i)]) Use logical_expression for convergence limit >> Testloop N= >> Testloop N= 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= >> Testloop N=333333

Nested loops and combination Example: exloop6.m Calculate 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 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>10000 break 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==0 continue end

The FOR loop Example : Write a Matlab script to calculate following expression for an entered x value

The FOR loop Example : Write a Matlab script to 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.

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; disp([num2str(ii),‘*’,num2str(jj),... ‘=’,num2str(product)]) end disp(‘end of inner loop’); end disp(‘end of outer loop’); 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