# Loops For loop for n = [2 5 8 7 3] code end While loop while a ~= 3 code end.

## Presentation on theme: "Loops For loop for n = [2 5 8 7 3] code end While loop while a ~= 3 code end."— Presentation transcript:

Loops For loop for n = [2 5 8 7 3] code end While loop while a ~= 3 code end

The if else command Note – many elseifs are allowed, but only 1 “else”

Variable values by example 1 3 1 6 1 9 2 3 2 6 2 9 3 3 6 3 9 4 3 4 6 4 9 index1index2 All possible combinations of the indices are generated.

Prior example – compounded interest until the amount doubles: value = 1000; for year = 1:1000 value = value * 1.08; disp([num2str(year),' years: \$ ',num2str(value) ]) if value > 2000 break end for loop terminated with break

Expected output:

while version format bank value = 1000; while value < 2000 value = value * 1.08; disp(value) end

Example – Collecting and storing data until a zero is entered: x = [ ]; new = 1; while new ~= 0 new = input('enter value '); x = [ x, new ]; end x = x(1:end–1) empty array to drop the zero initialize

Example – Getting valid keyboard input: E.g. forcing the user’s input to be between 0 and 10: x = –3; while ( x 10 ) x = input( 'type a value ' ); end

or: x = input('enter value '); while (x 10) disp('invalid choice'); x = input('enter value '); end disp('finally!');

Example – computing pi:

Example – “infinite” Hi-Lo: numb = round (10*rand(1)); done = 0; while ~done guess = input('guess'); if guess = = numb disp( 'You got it !!!' ); done = 1; elseif guess > numb disp('too high') else disp('too low') end initialization single guess loop control

3-by-3 array for the board: – Empty cell = 0 – X = +1 – O = – 1 Game end: – Winner if row, col, or diag sum = +3 or –3 – Draw is no zeros left Loop for game: – Initial move (X) plus 4 pairs of moves – Break if winner

Flowchart:

Program Outline:

Program Details: Initialization

Board Graphic

Get and Show First Move (X)

Start Loop with the Second Player

Check for Victory by O

Finish Loop with the First Player

Check for a Draw % check for draw if all(result ~= 0) & (sum(sum(abs(board))) == 9) disp('Nobody wins') end

Typical Output

Download ppt "Loops For loop for n = [2 5 8 7 3] code end While loop while a ~= 3 code end."

Similar presentations