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

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

    21-Dec-2015
  • Category

    Documents

  • view

    239
  • download

    1

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

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 elseifsare allowed,

but only 1 “else”

Variable values by example

1 31 61 92 32 62 93 33 6 3 94 34 64 9

inde

x1in

dex2

All possible combinationsof the indices are generated.

Prior example – compounded interest untilthe amount doubles:

value = 1000;

for year = 1:1000

value = value * 1.08;

disp([num2str(year),' years: $ ',num2str(value) ])

if value > 2000

break

end

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 < 0 ) | ( x > 10 )

x = input( 'type a value ' );

end

or:

x = input('enter value ');

while (x<0)|(x>10)

disp('invalid choice');

x = input('enter value ');

end

disp('finally!');

Example – computing pi:

...13

4

11

4

9

4

7

4

5

4

3

44

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

end

initialization

single guess

loopcontrol

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:

Initialization

Get X move Get O moveO

wins?

Get X move

Xwins?

GameOverDraw?

Yes

YesYes

No

No

No

GameOver

GameOver

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