more on logic today we look at the for loop and then put all of this together to look at some more...
TRANSCRIPT
More on Logic• Today we look at the for loop and then put all of this
together to look at some more complex forms of logic that a program will need
• The while and do loops are most commonly used when the condition is based on an input – that is, the user will decide whether to execute the loop again
or not• We might instead have a limit on the number of times
we want to execute the loop body – then we will use the for loop
• The for loop is sometimes referred to as a counting loop– it counts the number of iterations performed– we can make the for loop count from 1 to 10, from 1000
down to 1, from 0 to 100 skipping every other number, …
Structure of a for loop
for ( initialization ; condition ; increment ) statement;
Reservedword
The initialization portionis executed once
before the loop begins
The statement isexecuted until the
condition becomes false
The increment portion is executed at the end of each iteration
Initialize the loop variable(s)Check the condition
if true, execute the body
Perform the increment which might alter the conditionincrement
statement
true
conditionevaluated
false
initialization
For loop examples• Iterate 100 times
for (int i = 0; i < 100; i = i+1) System.out.println(i);
• Iterate from 1000 to 1for (i = 1000; i >= 1; i = i-1)
System.out.println(i);• Iterate from a to b (a and b are ints)
for (int j = a; j < b; j++)…;
• Iterate from 0 to 1000 by 2’sfor (j = 0; j < 1000; j += 2)
…;
The variable used inthe parens is known asthe loop index
The loop index can bedeclared right thereor earlier in the program
For Loop Versus While Loop• When having to perform some action a known
number of times, we use the for loop instead of the while loop because it is more convenient and readable
- Example: print the square of each integer from 1 to 25
value = 1;while (value < = 25) { System.out.print(value + " squared is " + value * value); value = value + 1; }
for (value = 1; value < = 25; value++) System.out.print(value + " squared is " + value * value);
Another for loop example
• Here is a variation of the averaging program – first ask the user the number of items to average:
System.out.print(“How many numbers do you have to enter? ”);x = in.nextInt( );for (i=0; i<x; i++) { System.out.print(“Enter value #” + i + “: ”); num = in.nextInt( ); sum += num;} average = ((float) sum) / x;
Nested For Loop Example
for (i = 1;i <=5; i++) { for (j = 1; j <=5; j++) System.out.print(" " + i*j); System.out.println(); }
If n = 5, this outputs:1 2 3 4 52 4 6 8 103 6 9 12 154 8 12 16 205 10 15 20 25
Notice that it doesn’t quite line up.
We refer to the two loops as the “outer” loop and the“inner” loop. The outer loop iterates 5 times, each time through,the inner loop iterates 5 times, so the inner loop body executesa total of 25 times
Notice how we used { } in the outer loop but not the inner. Why?
Logic Controlling Your Program• Without selection or iteration statements, our programs are
sequential– they do the same thing every time we run them, just on different data
• In order to make a program vary with respect to input, or to make decisions and act according to those decisions, we need control statements– selection (if, if-else) decide what instructions to execute and what to skip– iteration decides what instructions to repeat and how many times they
should be repeated• A basic program structure might look like this:
– Initialize variables as needed (for instance, if we are counting, set count = 0)– Enter a loop and repeat while the program should continue
• Input from the user for this iteration• Update variables, decide what to do for this set of inputs• Output results• If we should continue, go back to the top of the loop
– Finalize any values (such as computing an average) and output the final results of the program
Game Strategy• For a 2-player computer game (human vs. computer),
here is our typical logic:– Initialize the game– While neither player has won the game yet
• Output the current game set up (if applicable)• Get the human’s move and update the game (update the board if it is a
board game)– make sure that it is a legal move or ask again
• Check to see if the human has won, if so, leave the while loop, otherwise continue
• Decide what move the computer should make– this may require the use of some clever algorithm, possibly using Artificial
Intelligence• Check to see if the computer has won, if so, leave the while loop
– Output the result of the game
Implementation Details• To control the while loop, we might use a boolean
variable done which is false if no one has won the game yet and changed to true once someone has won– done = false;– while(!done) {…}
• How do we determine if someone has won the game?– That will be game-dependent– For each game, we will need code that looks like this:
• if(condition to determine if someone has won) done=true;– We would use this after both the human and
computers’ turns– Prior to the computer’s turn, we would also do:
• if(!done) {computer’s turn goes in here}
Human’s Turn• We use JOptionPane to get the user’s input, but what
will the input look like? – Depends on the game
• consider chess, we need the position of the piece to move and the position where they are moving it to
• Now we must verify that the move is legal – We will use a do-while loop to get input and verify,
as long as they are entering an illegal move, we continue to loop• do { … get user input … } while(user input is invalid);• for instance, in tic-tac-toe, we might number the tic-tac-
toe board using numbers 1-9, so (input >= 1 && input <= 9) – we would also have to make sure that the input was not already selected – we will see how to do this next week
Human/Human Games• If two humans are playing, our previous strategy is used except
that we change– Decide what move the computer should make
• To – Output the current game set up (if applicable)– Get the human’s move and update the game (update the board if it is a
board game)• make sure that it is a legal move or ask again
– Check to see if the human has won, if so, leave the while loop, otherwise continue
• If we have more than 2 players, we will need nested loops, the outer while loop that iterates while no one has won, and an inner for loop that iterates for each player– for(i=0;i<numPlayers;i++) {
• Output the current game set up (if applicable)• Get player i’s move and update the game (update the board if it is a board
game)– make sure that it is a legal move or ask again
• Check to see if player i has won, if so, leave the while loop, otherwise continue
Example Game: Dumb Board Gameint die, player1, player2;Random generator=new Random();player1=1; player2=1; // start both players at square 1while(player1<=49&&player2<=49) { die=generator.nextInt(6)+1; player1+=die; System.out.println("You roll " + die + " and are now at square " + player1); if(player1<=49) {
die=generator.nextInt(6)+1; player2+=die; System.out.println("I roll " + die + " and am now at square " + player2);
}}if(player1>player2) System.out.println("You win!");else if(player2>player1) System.out.println("I win!");else System.out.println("Its a tie");
Games With Strategies• The previous game required no strategies – we just take
turns rolling the die– what if we required human input to make a move? – first we have to ensure that the move is legal– next we have to determine if the move causes us to win the
game– finally we have to add logic for the computer to select a move
• Let’s consider a game called 15– we start with 15 matchsticks – each player takes a turn of removing 1-3 matchsticks– whoever is left with 1 matchstick loses
• so we have to make sure that the human’s choice is 1-3 and that at least 1 matchstick remains
– the computer needs a strategy• dumb strategy: randomly choose between 1 and 3• slightly better: see if there are 2, 3 or 4 left and if so, select enough to
leave 1 remaining so that the human loses• a smart strategy is shown in the program that follows
Fifteen (partial)Scanner in = new Scanner(System.in);int matches = 15, choice = 0, turn = 0; while(matches > 1) { do { turn=0; // human’s choice
System.out.print("How many matches will you take? (1-3) " ); choice = in.nextInt( );
} while (choice <1 || choice > 3 || choice > (matches-1)); matches -= choice; System.out.println("You chose " + choice + " mathces leaving " + matches); if(matches > 1) { // still matches left, my turn turn=1; if(matches <= 4) choice = 4 – matches + 1;
else { if(matches % 4 == 1) choice = Math.abs(generator.nextInt()) % 3 + 1; else if(matches % 4 == 0) choice = 3;
else if(matches % 4 == 2) choice = 1; else choice = 2;}matches -= choice;
System.out.println("I choose " + choice + " matches leaving " + matches);}if(turn = = 0) System.out.println(" Human wins! ");else System.out.println(" Computer wins! ");
A Tic-Tac-Toe Strategy• First, the computer checks to see if the choice is
“forced”– check to see if the computer can win on the next
move, if so, take it– check to see if the opponent can win on the next
move, if so, block it
• If not, use strategy to find the best open square– see if the center square is open, if so, take it– if any of the 4 corners are available, take it– otherwise randomly select an interior square
• Is this the best strategy available? • A player might want to try to set up a no-lose
situation – see to the right where X would place the next move in
the center square• The strategy above does not pursue this
X O
O
X