Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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, …

2 Structure of a for loop for ( initialization ; condition ; increment ) statement; Reservedword The initialization portion is executed once before the loop begins The statement is executed 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 condition increment statement true condition evaluated false initialization

3 For loop examples Iterate 100 times for (int i = 0; i < 100; i = i+1) System.out.println(i); Iterate from 1000 to 1 for (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’s for (j = 0; j < 1000; j += 2) …;

4 Using the for 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);

5 Another for loop example Here is a variation of the averaging program – first ask the user the number of items to average: x = Integer.parseInt(JOptionPane.showInputDialog (null, " How many numbers do you have to enter? " )); for (i=0; i<x; i++) { num = Integer.parseInt(JOptionPane.showInputDialog (null, " Enter value # " + i )); sum += num; } average = ((float) sum) / x;

6 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: 12 3 4 5 24 6 8 10 36 9 12 15 48 12 16 20 510 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 executes a total of 25 times Notice how we used { } in the outer loop but not the inner. Why?

7 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

8 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

9 How do we Implement our Strategy? We might use a boolean variable done to determine if a player has won yet –done = false; –while(!done) {…} 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 –we will use if statements to determine if either player has won the game and if so, we set won to true –we will use if statements to generate the computer’s move

10 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

11 Example Game: Dumb Board Game int die, player1, player2; Random generator=new Random(); player1=1; player2=1; // start both players at square 1 while(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");

12 Games With Strategies The previous game required no strategies – we just take turns rolling the die –what if we had 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 there is a better strategy available though

13 Fifteen (partial) int matches = 15, choice = 0, turn = 0; while(matches > 1) { do { turn=0; // human’s choice choice = Integer.parseInt(JOptionPane.showInputDialog( "How many matches will you take? (1-3)")); } while (choice 3 || choice > (matches-1)); matches -= choice; System.out.println("You chose " + choice + " 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! ");

14 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 course X O O X


Download ppt "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."

Similar presentations


Ads by Google