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.

Slides:



Advertisements
Similar presentations
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Advertisements

Computer Science 1620 Loops.
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.
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.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
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
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
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.
© 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.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
The switch Statement, DecimalFormat, and Introduction to Looping
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
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.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
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.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
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.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/29 The switch Statement The switch statement provides another way.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
The for loop.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Chapter Looping 5. The Increment and Decrement Operators 5.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.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
Structured Programming Structured Programming is writing a program in terms of only 3 basic control structures: sequence selection repetition We have already.
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Java Fundamentals 4.
REPETITION CONTROL STRUCTURE
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
Repetition-Counter control Loop
Repetition-Sentinel,Flag Loop/Do_While
Chapter 5: Control Structures II
Chapter 6 More Conditionals and Loops
Control Statements Loops.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Control Statements Loops.
Repetition Statements
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

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 statements and includes nested if-else statements and loops (introduced later today) –what if we have a list of possible actions to take based on an input or computed value? –for instance, we ask the user to input their age before playing a game if they enter anything < 0, we want to output an error message if they enter between 1 and 8, we might say that they are too young to play this game if they enter between 18 and 24, we might tell them to grow up and quit playing games if they enter anything over 24, we might laugh at them any other age is ok for our game –how do we design the logic to handle such a situation?

Nested Statements Let’s try to implement the previous example: –age < 0: error –age between 1 and 8: too young –age between 9 and 17: ok –age between 18 and 24: too old –age > 24: really really old Can we do this with an if statement or an if-else? No –we could solve this with 5 if statements, or with a nested if-else statement how do we test to see if an age is between 9 and 17? the conditions we’ve already seen have only tested a variable to one value, not two this will take some modification –or, we can use nested statements, this means that we have an if statement or an if-else statement as the statement inside of the if-clause or the else-clause or both

Example if (age < 0) output=“error”; else if(age<=8) output=“too young”; else if(age<=17) output=“ok”; else if(age<=24) output=“too old”; else output=“really really old”; if(age < 0) output=“error”; if(age<=8) output=“too young”; if(age<=17) output=“ok”; if(age<=24) output=“too old”; else output=“really really old”; Nested approach Note: indentation is not needed, its there for program readability Alternate approach – what is Wrong with this code? If you are 16, what will output be? We could solve this problem by reordering the if statements in the opposite order, but the new code would be inefficient – why?

import java.util.*; public class MinOfThree; { public static void main(String[] args) { Scanner in=new Scanner(System.in); int num1, num2, num3, min = 0; System.out.println(“Enter three integers, one at a time”); num1 = in.nextInt( ); num2 = in.nextInt( ); num3 = in.nextInt( ); if (num1 < num2) if (num1 < num3) min = num1; else min = num3; else if (num2 < num3) min = num2; else min = num3; System.out.println( " Minimum value is: " + min); } Another Example Notice the logic here, if num1 < num2, then we compare num1 and num3, to see which is smaller, if num1 < num3 then num1 is smallest (we already know num1is smaller than num2) if num1 is not less than num2, we compare num2 and num3

The Switch Statement An alternate approach to using the nested if-else structure is an instruction called switch We will use the switch statement if we are testing a single variable against a list of values Structure: –switch (variable) { case val 1 : statement 1 ; case val 2 : statement 2 ; case val 3 : statement 3 ; … case val last : statement last ; default : defaultstatement; } Compare variable with val1, val2, … and pick which statement to execute based on which value the variable matches

Switch Example switch (grade) { case ‘A’ : comment = " gold star " ; break; case ‘B’ : comment = " silver star " ; break; case ‘C’ : comment = " bronze star " ; break; case ‘D’ : comment = " no star " ; break; case ‘F’ : comment = " demerit " ; break; default : comment = " error, illegal letter grade! " ; } In this example, comment is a String which is assigned a value based on the student’s letter grade default is used as an error checking mechanism here – if reached, then the grade is an illegal grade NOTE: the word break is used to exit the switch statement, default is used as a final else clause for the switch

Which Statement Should You Use? When it comes to selection, you have five possibilities: –if statement –if-else statement –group of if statements –nested if-else statement –switch statement If there is only one action, then use the if statement If two actions, one if the condition is true, one if the condition is false, then use the if-else statement If you have a series of possibilities, which should you use? –Switch statement if the possibility is based on a single variable and the variable is an integral data type (integer, character or a user defined type that is ordinal) –Otherwise, use the nested if-else statement

Compound Conditions Recall the code to the right, what is wrong with it? –there is improper logic –we need to replace this condition with a compound condition test two things: if age > previous upper limit and also if age <= current upper limit –we create compound conditions by connecting them together with logic operators –there are 3 forms of logic operators used in Java: and (denoted as &&) – all conditions must be true for the compound condition to be true or (denoted as ||) – at least one condition must be true for the compound condition to be true not (denoted as !) – the item is inverted (true becomes false, false becomes true) if(age < 0) output=“error”; if(age<=8) output=“too young”; if(age<=17) output=“ok”; if(age<=24) output=“too old”; else output=“really really old”; if (age > 8 && age <=17) output=“ok”;

Repetition What happens if we want to do some action multiple times? –For instance, we want to count the number of times it takes when rolling a 6-sided die until we roll a 6 We write a program that rolls the 6-sided die once and outputs the result, and then we could run the program over and over until we get a 6, but this is both tiresome and requires that the user count the number of times we ran the program –The better approach is to use a repetition statement which would keep running the same random number instruction over and over until it it a 6, so we will use a repetition control statement –There are three forms of repetition statements in Java: While loops Do loops For loops

The While Statement The while statement evaluates a condition –if that condition is true, the body of the while statement is executed and the process is repeated –If the condition is false, the rest of the statement is skipped and control continues with the next instruction after the while statement while ( condition ) statement; while is a reserved word If the condition is true, the statement is executed. Then the condition is evaluated again. statement true condition evaluated false

Example import java.util.Random; public class SixRoller { public static void main(String[] args) { int count=1, die; Random g = new Random(); die=g.nextInt(6)+1; System.out.println("The first roll is a " + die); while(die!=6) { die=g.nextInt(6)+1; count++; System.out.println("The next roll is a " + die); } System.out.println("It took " + count + " rolls to get a 6"); }

Example Let’s write a loop that will compute the powers of 2 that are less than –We start with a variable set equal to 1 –We loop while that variable <= –Inside the loop, we print the value of the variable and then multiply it by 2 Notice that since the loop “body” is more than a single statement, we enclose it in { } to make it a block int value = 1; while (value < ) { System.out.println(value); value *= 2; } outputs: …

Sentinel Values In the two examples, we iterated until we reached some value of interest (die == 6, value >= ) We will often use While loops to repeat some action such as: input some value, perform a calculation, output a result, repeat until the user is done –How do we know if the user is done? –We could ask the user or we could base the decision on the input value – this is known as a sentinel value Example: input a list of integers until the user enters a negative number, and compute the sum of these numbers

Sum Example Scanner in = new Scanner(System.in); int value, sum; … sum = 0; System.out.print(“Enter a positive integer, negative to quit: ”); value = in.nextInt( ); while (value >= 0) { sum += value; System.out.print(“Enter another positive integer, negative to quit: ”); value = in.nextInt( ); } System.out.println( " The sum of the numbers you entered is " + sum); value < 0 is our sentinel for the loop Notice that we repeated these Instructions – why? Initialize sum before we enter the loop

A slightly different version int value, sum; … sum = 0; System.out.print(“Enter a positive integer, negative to quit: ”); value = in.nextInt( ); while (value >= 0) { sum += value; } System.out.println( " The sum of the numbers you entered is " + sum); Notice in this version we don’t ask for the next value – this means that value never changes – if it never changes, then it is always the original value, if that value was >= 0, it will always be >= 0 and thus the loop will never stop – this is an infinite loop

Infinite Loops Careless (and even careful) programmers will write infinite loops This is a major problem when using the while loop –The basic idea behind the loop is to continue executing while a condition is true If that condition is based on an input value, then the program must input a new value during each iteration so that the user can change the value to one that exits the loop Otherwise, the value never changes and the loop never stops! Exiting an infinite loop –if you suspect that your program is caught in an infinite loop, about your only recourse is to stop the program Press control-C on the keyboard

Computing an Average int number, count, sum; float average; sum = 0; count = 0; System.out.print(“Enter a number, 0 to end”); number = in.nextInt( ); while (number > 0) { sum += number; count++; System.out.print(“Enter another number, 0 to end”); number = in.nextInt( ); } average = (float) sum / count; System.out.print( " The average of your " + count); System.out.println( " numbers is " + average); This program is similar to the sum program from before, but we are also counting the number of inputs using the count variable 0 (or any negative number) is our sentinel value what happens if the user enters 0 to begin with?

The do Loop The do loop is similar to the while loop but is a post-test loop, the while loop is a pre-test loop The Do loop starts with the reserved word do followed by the loop body and then the reserved word while and the condition –The difference is the flow of control – here, the condition is not evaluated until after the body of the loop executes do { statement; } while ( condition ) Uses both the do and whilereservedwords true condition evaluated statement false

While vs. Do The only difference between these two statements is when the condition is evaluated –While: evaluated before executing the loop body –Do: evaluated after executing the loop body If you want to automatically execute the loop body at least once, use the Do loop If you don’t want to do the body if the condition is not true, use the While loop statement true condition evaluated false true condition evaluated statement false

Using Loops to Verify Input Consider a situation where we want the user to input one of a set of values that constitute a legal input What if the user enters an illegal input? –Example: input a non-negative integer and take the square root –If x < 0, we would get a run- time error when the sqrt operation is invoked! A solution to this problem is to place the prompt and input statements inside a loop that only terminates once the user has entered the right value –We will use a do statement for this since we will want the user to input the value at least one time System.out.print(“Enter a non-negative number ”); x = in.nextInt( ); y = Math.sqrt((double) x); do { System.out.print(“Enter a non-negative number ”); x = in.nextInt( ); } while (x < 0); y = Math.sqrt((double) x);