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