Loops & More 1.Conditionals (review) 2.Running totals and Running products 3.the for loop, examples 4.Nesting for loops, examples 5.Common errors 1.

Slides:



Advertisements
Similar presentations
Switch code for Lab 4.2 switch (input) { /* input is a variable that we will test. */ case 'M': printf("The prefix is equal to 1E6.\n"); break; case 'k':
Advertisements

Objectives In this chapter, you will learn about:
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Repeating Actions While and For Loops
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
True BASIC Ch. 6 Practice Questions. What is the output? PRINT X LET X = -1 PRINT X FOR X = 4 TO 5 STEP 2 PRINT X NEXT X PRINT X END.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
Lecture 12 Another loop for repetition The while loop construct © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
1. Definition and General Structure 2. Small Example 1 3. Simplified Structure 4. Short Additional Examples 5. Full Example 2 6. Common Error The for loop.
Review for Exam2 Key Ideas 1. Key Ideas: Boolean Operators (2 > 3) || (3 < 29.3) A.True B.False C.Impossible to determine (22 > 3) && (3 > 29.3) A.True.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
1. Example 1 – Averages 2. Example 2 – Rolling Dice 3. Example 3 – Number Analysis 4. Example 4 - Divisibility ( while ) Additional Examples on for Loops.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Introduction to Loops For Loops. Motivation for Using Loops So far, everything we’ve done in MATLAB, you could probably do by hand: Mathematical operations.
Designing While Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Review while loops Control variables Example Infinite loop
© The McGraw-Hill Companies, 2006 Chapter 3 Iteration.
Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1.
Beginning C For Engineers Fall 2005 Lecture 3: While loops, For loops, Nested loops, and Multiple Selection Section 2 – 9/14/05 Section 4 – 9/15/05 Bettina.
CSE123 - Lecture 4 Structured Programming- Loops.
Chapter 5: Looping. Using the while Loop Loop – A structure that allows repeated execution of a block of statements Loop body – A block of statements.
26/06/ Iteration Loops For … To … Next. 226/06/2016 Learning Objectives Define a program loop. State when a loop will end. State when the For.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC530 Data Structures - LOOP 7/9/20161.
ECE Application Programming
Lesson #5 Repetition and Loops.
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
ECE Application Programming
Repetition Structures Chapter 9
2008/09/22: Lecture 6 CMSC 104, Section 0101 John Y. Park
Lecture 7: Repeating a Known Number of Times
Lesson #5 Repetition and Loops.
Chapter 5: Control Structures II
Chapter 5: Control Structure
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Repetition-Counter control Loop
JavaScript: Control Statements.
Topics Introduction to Repetition Structures
Lecture 07 More Repetition Richard Gesick.
Computer Science 101 While Statement.
Lecture 4B More Repetition Richard Gesick
Control Structures - Repetition
Conditinoal Constructs Review
Arrays, For loop While loop Do while loop
Control Structure Senior Lecturer
- Additional C Statements
Lesson #5 Repetition and Loops.
Conditinoal Constructs Review
Java Programming Loops
Types of Flow of Control
3 Control Statements:.
Chapter 6: Repetition Statements
3.1 Iteration Loops For … To … Next 18/01/2019.
Week 6 CPS125.
Loop Statements & Vectorizing Code
CSC115 Introduction to Computer Programming
Let’s all Repeat Together
2.6 The if/else Selection Structure
Java Programming Loops
Loops.
Topics Introduction to Repetition Structures
Lesson #5 Repetition and Loops.
ICS103: Programming in C 5: Repetition and Loop Statements
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Loops & More 1.Conditionals (review) 2.Running totals and Running products 3.the for loop, examples 4.Nesting for loops, examples 5.Common errors 1

Ex4, algorithm Ask user for a list of surfaces in meters squared. Add all surfaces together. Stop asking when a negative/or null surface is entered! % start result at zero % get the first surface % As long as the current surface is positive % “running total”: add surface to total % ask for next surface value % display total surface to the screen 2

Ex4, initialization % start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) % As long as surface is positive % “running total”: add surfaces as they are given % ask for next surface value % display total surface to the screen 3

Ex4, initialization % start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive % “running total”: add surfaces as they are given % ask for next surface value % display total surface to the screen 4

Ex4, block of code %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value % display total surface to the screen 5

Ex4, change of condition %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input('Next surface: '); % display total surface to the screen 6

Ex4, fill in the code %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive while % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input('Next surface: '); end % display total surface to the screen 7

Ex4, condition %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive while surface>0 % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input('Next surface: '); end % display total surface to the screen 8

Ex4, continue %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive while surface>0 % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input('Next surface: '); end % display total surface to the screen fprintf('All surfaces add up to %.4f m^2.\n', sumSurfaces); 9

Ex4, output result 10

1. while (review) while is used to – repeat an unknown amount of time trap the user while invalid data is entered prompt the user for an unknown amount of values Give limited/unlimited attempts to username/password checks Overall syntax: initialize while condition(s) body of code, which MUST include a statement that updates the T/F status of the condition end

1. this while loop is complete 12 % prompt for a surface (and give directions) fprintf(‘Note: a negative/zero surface quits.\n’); surface = input(‘Enter surface (m2): ’); sumSurfaces = 0; %start result at zero % while surface is positive (i.e. valid) while surface>0 % keep track of sum sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input(‘Next surface: ’); end % display total surface to the screen fprintf(‘These %d surfaces add up to %.4f m2.\n’, nbSurfaces, sumSurfaces); Initialize (starting point) condition (continuing(true) point / stopping(false) point) updating the variable involved in the condition

2. Running totals (review) mytotal = mytotal + newScore; 13 “Add as you go…” 3058 mytotal 8 newScore 3066

2. Running totals (review) mytotal = 14 “Count as you go…” 3058 mytotal 8 newScore 3066

2. Running totals (review) mytotal = mytotal + newScore; 15 “Count as you go…” 3066 mytotal 8 newScore ?

2. Running totals (review) Applications of running total – sum values as they are entered – count values when they satisfy a criteria – count values when they do NOT satisfy a criteria – … ALWAYS initialize your variable (more than likely at 0, but not necessarily!) 16

Add the surfaces as you go… 17 % prompt for a surface (and give directions) fprintf(‘Note: a negative/zero surface quits.\n’); surface = input(‘Enter surface (m2): ’); sumSurfaces = 0; %start result at zero % while surface is positive (i.e. valid) while surface>0 % keep track of sum sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input(‘Next surface: ’); end % display total surface to the screen fprintf(‘These %d surfaces add up to %.4f m2.\n’, nbSurfaces, sumSurfaces);

Add a counter for nb of surfaces 18 % prompt for a surface (and give directions) fprintf(‘Note: a negative/zero surface quits.\n’); surface = input(‘Enter surface (m2): ’); sumSurfaces = 0; %start result at zero % while surface is positive (i.e. valid) while surface>0 % keep track of sum sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input(‘Next surface: ’); end % display total surface to the screen fprintf(‘These %d surfaces add up to %.4f m2.\n’, nbSurfaces, sumSurfaces); ?

2. Running Products Running total implies a “sum” Running “products”: result = result * newValue; You can even combine running totals and running products: %sum the volumes result = result + length*width*height; Make sure this is inside a loop! 19

3. Another type of loop Matlab has two loops, one for each method explained previously: while – Generic, all-purpose. Best used when the programmer does not know how many times the block of code needs to repeat. – Repeats while a CONDITION is true. for – A COUNTING loop. Best used when the programmer “knows” how many times the block of code needs to repeat. 20

3. for statement >> doc for for Execute statements a specified number of times Syntax for index = initval:step:endval program statements; end 21 initval:endval increments the index variable from initval to endval by +1, and repeats execution of program statements until index is greater than endval. initval:step:endval increments index by the value step on each iteration, or decrements when step is negative.

while vs. for mySum = 0; x = 1; while x<=10 mySum = mySum + x; x = x +1; end fprintf(‘Sum: %d.\n’, mySum); 22 For example, this loop counts from 1 to 10, by steps of +1 mySum = 0; for x = 1:10 mySum = mySum + x; end fprintf(‘Sum: %d.\n’, mySum); The range-operator ( : )

while vs. for : initialize (1) mySum = 0; x = 1; while x<=10 mySum = mySum + x; x = x +1; end fprintf(‘Sum: %d.\n’, mySum); 23 Both loops initialize mySum = 0; for x = 1:10 mySum = mySum + x; end fprintf(‘Sum: %d.\n’, mySum);

while vs. for : condition (2) mySum = 0; x = 1; while x<=10 mySum = mySum + x; x = x +1; end fprintf(‘Sum: %d.\n’, mySum); 24 Both loops have a point where to stop mySum = 0; for x = 1:10 mySum = mySum + x; end fprintf(‘Sum: %d.\n’, mySum);

while vs. for : code to repeat (3) mySum = 0; x = 1; while x<=10 mySum = mySum + x; x = x+1; end fprintf(‘Sum: %d.\n’, mySum); 25 Both loops repeat a statement mySum = 0; for x = 1:10 mySum = mySum + x; end fprintf(‘Sum: %d.\n’, mySum);

while vs. for : update loop-variable (4) mySum = 0; x = 1; while x<=10 mySum = mySum + x; x = x+1; end fprintf(‘Sum: %d.\n’, mySum); 26 Both loop increase by +1 mySum = 0; for x = 1:10 mySum = mySum + x; end fprintf(‘Sum: %d.\n’, mySum); the default is +1

The for is a “counting” loop mySum = 0; x = 1; while x<=10 mySum = mySum + x; x = x+1; end fprintf(‘Sum: %d.\n’, mySum); 27 for - initialize, increment and condition are together mySum = 0; for x = 1:10 mySum = mySum + x; end fprintf(‘Sum: %d.\n’, mySum); the default is +1 The for loop is a “counting loop”

Loop “Unrolling” mySum = 0; x = 1; mySum = mySum + x; x = 2; mySum = mySum + x; x = 3; mySum = mySum + x; x = 4; mySum = mySum + x; x = 5; mySum = mySum + x; x = 6; mySum = mySum + x; x = 7; mySum = mySum + x; x = 8; mySum = mySum + x; x = 9; mySum = mySum + x; x = 10; mySum = mySum + x; fprintf('Sum: %d\n', mySum); 28 mySum = 0; for x = 1:10 mySum = mySum + x; end fprintf(‘Sum: %d.\n’, mySum);

Updating the surfaces… % prompt the user how many surfaces, check valid while end %loop that many times for %prompt for that surface %add the surfaces as we go end %indicate the total surface 29

Be friendlier to the user From this: To this: 30

CAUTION/HINTS input() does NOT work with placeholders. input() is meant to prompt the user for data, NOT to format an output. 31

Using an increment different than Perfect for single countdowns! – In countdowns, the increment is _____. initval:step:endval increments index by the value step on each iteration, or decrements when step is negative. Any ideas? – keywords to use? – which loop(s)? – possible issues?

Example2: Thrust of a rocket Rockets can have multiple engines. Each engine can have a different thrust. The user will chose how many engines, though MATLAB will generate all the numbers for a possible rocket design scenario. 33

Example2: Thrust of a rocket Step2: Assume 3 pairs (6 total) engines (fired at different times maybe..) Step3: TotalThrust = 2* sum of thrust per engine Step4: -For stability purposes, assume the number of engines needs to be even, and the thrusts go by 2. -Range of an engine thrust will be between lbs and lbs. 34

Example2: Thrust of a rocket Step5: Assume 6 engines, with the following generated by MATLAB: engines1: lbs engines2: lbs engines3: lbs total thrust = 2*( )*1000 = lbs Step6 35

Algorithm %prompt the user the amount of engines, check valid %start sum at zero %loop half that many times for %generate/display the thrust (rand) %sum up the thrusts end %calculate/display final thrust for the rocket 36

Possible Output #1 37

Possible Output #2 38

Common errors Decrement.. (But not really) for k = 10:1 fprintf(‘%d\n’,k); end Changing the loop variable within the for loop (or trying to..) for k = 1:2:5 fprintf(‘%d\n’,k); k = k+1; %a remain of the while loop??? end 39 Incremement by +2 or by +1 ??? What choice will MATLAB make?

Common errors Counting.. (But not really) for 1:10 fprintf(‘hi\n’); end 40

Key ideas The for loop is a counting loop The while loop can always be used BUT…the for loop is meant to count – The startvalue:step:endValue contains all necessary values for the loop to work. Nested for loops are absolutely possible! Actually, any construct ( if, switch, while, for ) can now be nested within each other. 41