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.

Slides:



Advertisements
Similar presentations
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Advertisements

Representing a Game Board In a game, we represent the action taking place using an array – In a very simple game, we use individual variables to represent.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
COMP 14 Introduction to Programming Mr. Joshua Stough February 16, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 6, 2005.
COMP 14 Introduction to Programming Miguel A. Otaduy May 21, 2004.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops – While, Do, For Repetition Statements Introduction to Arrays
FIT Objectives By the end of this lecture, students should: understand iteration statements understand the differences of for and while understand.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Chapter 5: Control Structures II (Repetition)
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Chapter 5 Loops.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 4 Loops Write code that prints out the numbers Very often, we want to repeat a (group of) statement(s). In C++, we have 3 major ways of.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
1-Dec-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Advanced Arithmetic, Conditionals, and Loops INFSY 535.
CS 0401 Debugging Hints and Programming Quirks for Java by John C. Ramirez University of Pittsburgh.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Decision Making and Branching (cont.)
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
COMP Loop Statements Yi Hong May 21, 2015.
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.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
© 2006 Pearson Education Chapter 3 Part 2 More about Strings and Conditional Statements Loops (for and while) 1.
REPETITION CONTROL STRUCTURE
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
CiS 260: App Dev I Chapter 4: Control Structures II.
Repetition-Sentinel,Flag Loop/Do_While
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Arrays, For loop While loop Do while loop
Outline Altering flow of control Boolean expressions
Module 4 Loops.
Control Statements Loops.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Control Statements Loops.
Learning Plan 4 Looping.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation 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 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

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) …; The variable used in the parens is known as the loop index The loop index can be declared right there or 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: 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;

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: 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?

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 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");

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) 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 + " 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