loops for loop for n = [2 5 8 7 3] code end while loop while a ~= 3 code end
Post on 21-Dec-2015
237 views
TRANSCRIPT
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
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 – “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
Check for a Draw
% check for draw
if all(result ~= 0) & (sum(sum(abs(board))) == 9)
disp('Nobody wins')
end