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
Introduction to Computing Science and Programming I
Advertisements

08 Deterministic iteration1May Deterministic iteration CE : Fundamental Programming Techniques.
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.
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.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
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.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
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.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Chapter 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
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.
CPS120: Introduction to Computer Science Decision Making in Programs.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
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.
Coding Design Tools Rachel Gauci. Task: Counting On Create a program that will print out a sequence of numbers from "1" to a "number entered”. Decision’s.
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.
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.
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
Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!
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.
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.)
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
COMP Loop Statements Yi Hong May 21, 2015.
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)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 3: Decisions 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
Loops A portion of a program that repeats a statement or a group of statements is called a loop. The statement or group of statements to be repeated is.
Module 4 Loops.
Control Statements Loops.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Control Statements Loops.
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) …;

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

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

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

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

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

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