Download presentation
Presentation is loading. Please wait.
1
Loops For loop for n = [2 5 8 7 3] code end While loop while a ~= 3 code end
2
The if else command Note – many elseifs are allowed, but only 1 “else”
3
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.
4
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
5
Expected output:
6
while version format bank value = 1000; while value < 2000 value = value * 1.08; disp(value) end
7
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
8
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
9
or: x = input('enter value '); while (x 10) disp('invalid choice'); x = input('enter value '); end disp('finally!');
10
Example – computing pi:
11
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
12
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
13
Flowchart:
14
Program Outline:
15
Program Details: Initialization
16
Board Graphic
17
Get and Show First Move (X)
18
Start Loop with the Second Player
19
Check for Victory by O
20
Finish Loop with the First Player
21
Check for a Draw % check for draw if all(result ~= 0) & (sum(sum(abs(board))) == 9) disp('Nobody wins') end
22
Typical Output
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.