Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.

Slides:



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

1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
Computer Science A 4 13/3. Goals To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
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 –For For Reading for this Lecture, L&L, Part of 5.8.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Java Program Statements Selim Aksoy Bilkent University Department of Computer Engineering
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.
C++ for Engineers and Scientists Third Edition
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
The switch Statement, DecimalFormat, and Introduction to Looping
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Lecture 10 Instructor: Craig Duckett. Assignment 2 Revision TONIGHT DUE TONIGHT Wednesday, August 5 th Assignment 3 NEXT DUE NEXT Monday, August 10 th.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Java Programming: From the Ground Up
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved For Loops October 16, 2013 Slides by Evan Gallagher.
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
Copyright © 2013 by John Wiley & Sons. All rights reserved. LOOPS CHAPTER Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30,
 Executes a block of code repeatedly  A condition controls how often the loop is executed  Most commonly, the statement is a block statement (set of.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Decisions Bush decision making.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC INTRO TO COMPUTING - PROGRAMMING If Statement.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
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.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CS0007: Introduction to Computer Programming
Slides by Evan Gallagher
Slides by Evan Gallagher
CompSci 230 S Programming Techniques
Lecture 4b Repeating With Loops
The switch Statement, and Introduction to Looping
Lecture 3- Decision Structures
Chapter 6 More Conditionals and Loops
Primitive Data, Variables, Loops (Maybe)
User input We’ve seen how to use the standard output buffer
Selected Topics From Chapter 6 Iteration
TK1114 Computer Programming
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
LOOPS.
Chapter 6 More Conditionals and Loops
Outline Altering flow of control Boolean expressions
Chapter 2 Programming Basics.
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Repetition Statements
Presentation transcript:

Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations

Copyright © 2014 by John Wiley & Sons. All rights reserved.2 Chapter Goals  To implement decisions using if statements  To implement while, for, and do loops  To understand nested loops  To develop strategies for testing your programs  To validate user input

Copyright © 2014 by John Wiley & Sons. All rights reserved.3 Decisions

Copyright © 2014 by John Wiley & Sons. All rights reserved.4 Performing Comparisons  Most programs need the ability to test conditions and make decisions based on the outcomes of those tests.  The primary tool for testing conditions is the if statement  If statement which tests whether a boolean expression has the value true or false.  Most of the conditions in a program involve comparisons, which are performed using the relational operators and the equality operators.

Copyright © 2014 by John Wiley & Sons. All rights reserved.5 Relational Operators  These operators test the relationship between two numbers, returning a boolean result. < Less than > Greater than <= Less than or equal to >= Greater than or equal to  Examples: 5 < 3  false 5 > 3  true 3 > 3  false 5 <= 3  false 5 >= 3  true 3 >= 3  true

Copyright © 2014 by John Wiley & Sons. All rights reserved.6 Relational Operators  operands can be of different types. If an int value is compared with a double value, the int value will be converted to double before the comparison is performed.  The arithmetic operators take precedence over the relational operators, so Java would interpret a - b * c < d + e as (a – (b * c)) < (d + e) Check for precedence with other operators:

Copyright © 2014 by John Wiley & Sons. All rights reserved.7 Equality Operators  Testing whether two values are equal or not equal is done using the equality operators: == Equal to != Not equal to  The equality operators have lower precedence than the relational operators.  Examples of the equality operators: 6 == 2  false 6 != 2  true 2 == 2  true 2 != 2  false

Copyright © 2014 by John Wiley & Sons. All rights reserved.8

9 Logical Operators  You often need to combine the results of comparisons when making complex decisions  The && operator is called and Yields true only when both conditions are true.  The || operator is called or Yields the result true if at least one of the conditions is true.  The ! Operator is called not Yields negation  ! is a unary operator. && and || are binary operators.  All logical operators expect boolean operands and produce boolean results

Copyright © 2014 by John Wiley & Sons. All rights reserved.10 Logical Operators

Copyright © 2014 by John Wiley & Sons. All rights reserved.11 Logical Operators  To test if water is liquid at a given temperature: if (temp > 0 && temp < 100) { System.out.println("Liquid"); } boolean found = false; if(!found) { //do something }

Copyright © 2014 by John Wiley & Sons. All rights reserved.12 Precedence and Associativity of operators

Copyright © 2014 by John Wiley & Sons. All rights reserved.13 Precedence and Associativity of And, Or, and Not  The ! operator is right associative.  The && and || operators are left associative.  Java would interpret a = d && e == f as ((a = d)) && (e == f)  Another example

Copyright © 2014 by John Wiley & Sons. All rights reserved.14 The if Statement  The if statement allows a program to test a condition  When the if statement is executed: the BooleanExpression is evaluated. If it’s true, then statement is executed. If it’s false, statement is NOT executed. if(BooleanExpression) statement; if(BooleanExpression) { statement1; statement2;... } OR Block: Set of statements within curly braces int actualFloor = floor; if (floor > 13) { actualFloor--; } E.g.

Copyright © 2014 by John Wiley & Sons. All rights reserved.15 The if-else Statement  Flowchart with two branches:  When the if statement is executed: the BooleanExpression is evaluated. If it’s true, then statement/block1 inside if is executed. If it’s false, statement/block2 inside else is executed instead. if(BooleanExpression) statement or block 1 else statement or block 2 int actualFloor = floor; if (floor > 13){ actualFloor--; } else{ actualFloor = floor; } E.g.

Copyright © 2014 by John Wiley & Sons. All rights reserved.16 The if-else if Statement  Test a series of conditions (multiple alternatives)  If BooleanExpression1 is true, then statement or block 1 is executed.  If BooleanExpression1 is false, then BooleanExpression2 is tested. If BooleanExpression2 is true, then statement or block 2 is executed. If BooleanExpression2 is false, then statement or block 3 is executed.  You can have as many else if clauses as is needed.  else clause is optional if (BooleanExpression1) statement or block 1 else if(BooleanExpression2) statement or block 2 else statement or block 3

Copyright © 2014 by John Wiley & Sons. All rights reserved.17 The if-else if Statement  As soon as one of the tests succeeds: The effect is displayed No further tests are attempted.  If none of the tests succeed: The final else clause applies

Copyright © 2014 by John Wiley & Sons. All rights reserved.18 The if-else if Statement  E.g. if (richter >= 8.0) { description = "Most structures fall”; } else if (richter >= 7.0) { description = "Many buildings destroyed”; } else if (richter >= 6.0) { description = "Many buildings considerably damaged, some collapse”; } else if (richter >= 4.5) { description = "Damage to poorly constructed buildings”; } Note that else clause is optional.

Copyright © 2014 by John Wiley & Sons. All rights reserved.19 The if-else if Statement  In this example, must use if/else if/else sequence, not just multiple independent if statements  Error: if (richter >= 8.0) // Didn't use else { description = "Most structures fall”; } if (richter >= 7.0) { description = "Many buildings destroyed”; } if (richter >= 6.0) { description = "Many buildings considerably damaged, some collapse”; } if (richter >= 4.5) { "Damage to poorly constructed buildings”; }  The alternatives are no longer exclusive.

Copyright © 2014 by John Wiley & Sons. All rights reserved.20 Syntax 5.1 The if Statement

Copyright © 2014 by John Wiley & Sons. All rights reserved.21 Programming Question  Write a class IfTester. In the main method define two variables score and grade. score represents a score of a student for a given test. grade is a character representing the grade of the student based on his/her score. Write a set of statements to prompt the user for a score, find and print the grade of the student. Use following criteria for grading: score grade A 80-89B 70-79C <70D Sample output:

Copyright © 2014 by John Wiley & Sons. All rights reserved.22 Answer import java.util.Scanner; public class IfTester { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter score: "); int score = sc.nextInt(); char grade; if(score>=90 && score<=100) { grade = 'A'; } else if(score>=80) { grade='B'; } else if(score>=70) { grade='C'; } else { grade='D'; } System.out.println("Score ="+score+" Grade="+grade); } IfTester.java

Copyright © 2014 by John Wiley & Sons. All rights reserved.23 Relational Operator Examples

Copyright © 2014 by John Wiley & Sons. All rights reserved.24 Loops

Copyright © 2014 by John Wiley & Sons. All rights reserved.25 Loops A part of a program is repeated over and over, until a specific goal is reached A statements in a loop are executed while a condition is true. For calculations that require repeated steps

Copyright © 2014 by John Wiley & Sons. All rights reserved.26 Types of Loops  Java has three loop statements: while do for  All three use a boolean expression to determine whether or not to continue looping.  All three require a single statement as the loop body. This statement can be a block, however.

Copyright © 2014 by John Wiley & Sons. All rights reserved.27 Types of Loops  Which type of loop to use is mostly a matter of convenience. The while statement tests its condition before executing the loop body. The do statement tests its condition after executing the loop body. The for statement test condition before executing the loop body. The for statement is most convenient if the loop is controlled by a variable whose value needs to be updated each time the loop body is executed.

Copyright © 2014 by John Wiley & Sons. All rights reserved.28 The while Loop  How can you “Repeat steps while the balance is less than $20,000?”  With a while loop statement  Syntax while (condition) { statements }  As long condition is true, the statements in the while loop execute. while (condition) { statements }

Copyright © 2014 by John Wiley & Sons. All rights reserved.29 The while Loop  Investment problem: You put $10,000 into a bank account that earns 5 percent interest per year. How many years does it take for the account balance to be double the original investment?

Copyright © 2014 by John Wiley & Sons. All rights reserved.30 The while Loop  Investment problem: You put $10,000 into a bank account that earns 5 percent interest per year. How many years does it take for the account balance to be double the original investment?  The code: double balance = 10000; double targetBalance = balance *2; int year = 0; while (balance < targetBalance) { year++; double interest = balance * 5/ 100; balance = balance + interest; }

Copyright © 2014 by John Wiley & Sons. All rights reserved.31 Complete program public class WhileTester2 { public static void main( String args[] ) { double balance = 10000; double targetBalance = balance *2; int year = 0; while (balance < targetBalance) { year++; double interest = balance * 5/ 100; balance = balance + interest; } System.out.println("It takes "+year +" years to double the balance"); } // end main } // end class whileTester2.java

Copyright © 2014 by John Wiley & Sons. All rights reserved.32 Syntax 6.1 while Statement

Copyright © 2014 by John Wiley & Sons. All rights reserved.33 The while Loop  For a variable declared inside a loop body: Variable is created for each iteration of the loop And removed after the end of each iteration double balance = 10000; double targetBalance = balance *2; int year = 0; while (balance < targetBalance) { year++; double interest = balance * 5/ 100; balance = balance + interest; } // interest no longer declared here

Copyright © 2014 by John Wiley & Sons. All rights reserved.34 Programming Question  Calculate.java  Write a Java application that calculates and prints the sum of the integers from 1 to 10. Use a while statement to loop through the calculation and increment statements. The loop should terminate when the value of x becomes 11

Copyright © 2014 by John Wiley & Sons. All rights reserved.35 Answer public class Calculate { public static void main( String args[] ) { int sum, x; x = 1; sum = 0; while ( x <= 10 ) { sum += x; ++x; } System.out.println( "The sum is: " + sum ); } // end main } // end class Calculate.java

Copyright © 2014 by John Wiley & Sons. All rights reserved.36 while Loop Examples

Copyright © 2014 by John Wiley & Sons. All rights reserved.37 for loop  A compact way to iterate over a range of values  Syntax: for (initialization; termination; increment) { statement(s) }  E.g. print the numbers 1 through 10 class ForDemo { public static void main(String[] args){ for(int i=1; i<11; i++){ System.out.println("Count is: " + i); }

Copyright © 2014 by John Wiley & Sons. All rights reserved.38 Syntax 6.2 for Statement

Copyright © 2014 by John Wiley & Sons. All rights reserved.39 The for Loop  The initialization is executed once, before the loop is entered.  The condition is checked before each iteration.  The update is executed after each iteration.

Copyright © 2014 by John Wiley & Sons. All rights reserved.40 The for Loop  A for loop can count down instead of up: for (int counter = 10; counter >= 0; counter--) { //do something }  The increment or decrement need not be in steps of 1 : for (int counter = 0; counter <= 10; counter += 2) { //do something }

Copyright © 2014 by John Wiley & Sons. All rights reserved.41 The for Loop  If the counter variable is defined INSIDE the loop header, It does not exist after the loop for (int counter = 1; counter <= 10; counter++) {... } // counter no longer declared here  If you declare the counter variable BEFORE the loop, You can continue to use it after the loop int counter; for (counter = 1; counter <= 10; counter++) {... } // counter still declared here

Copyright © 2014 by John Wiley & Sons. All rights reserved.42 Programming Question  Calculate2.java  Write class Calculate2.java that prints all numbers in range 1,10 (inclusive) evenly divisible by 3

Copyright © 2014 by John Wiley & Sons. All rights reserved.43 Answer public class Calculate2 { public static void main( String args[] ) { int sum; sum = 0; for(int x=1;x<=10;x++) { if(x%3==0) System.out.println(x); } //OR //for(int x=3;x<=10;x+=3) //{ // System.out.println(x); //} } // end main } // end class Calculate2.java

Copyright © 2014 by John Wiley & Sons. All rights reserved.44 The for Loop Sample for loop: for (int counter = 1; counter <= 10; counter++) { System.out.println(counter); } while loop equivalent int counter = 1; // Initialize the counter while (counter <= 10) // Check the counter { System.out.println(counter); counter++; // Update the counter }

Copyright © 2014 by John Wiley & Sons. All rights reserved.45 Question  When should we use while loop over for loop and viz versa?

Copyright © 2014 by John Wiley & Sons. All rights reserved.46 The for Loop Examples

Copyright © 2014 by John Wiley & Sons. All rights reserved.47 The do Loop  Executes the body of a loop at least once and performs the loop test after the body is executed.  Used for input validation To force the user to enter a value less than 100 int value; do { System.out.print("Enter an integer < 100: "); value = in.nextInt(); }while (value >= 100);

Copyright © 2014 by John Wiley & Sons. All rights reserved.48 Complete Program import java.util.Scanner; class DoWhileDemo { public static void main(String[] args) { Scanner in = new Scanner(System.in); int value; do { System.out.print("Enter an integer < 100: "); value = in.nextInt(); }while (value >= 100); }

Copyright © 2014 by John Wiley & Sons. All rights reserved.49 Nested Loops  One loop inside another loop.  E.g for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 2; j++){ System.out.println(“i=“ +i+ “j=”+j); } }

Copyright © 2014 by John Wiley & Sons. All rights reserved.50 Question  What is the output of the following nested for loop: for (int i = 1; i <= 6; i++) { for (int j = 1; j <= i; j++) { System.out.print(“*"); } System.out.println(); }

Copyright © 2014 by John Wiley & Sons. All rights reserved.51 Answer  Output: * ** *** **** ***** ****** for (int i = 1; i <= 6; i++) { for (int j = 1; j <= i; j++) { System.out.print(“*"); } System.out.println(); }

Copyright © 2014 by John Wiley & Sons. All rights reserved.52 Nested Loop Examples

Copyright © 2014 by John Wiley & Sons. All rights reserved.53 Nested Loop Examples

Copyright © 2014 by John Wiley & Sons. All rights reserved.54 Common Error: Infinite Loops  Example: forgetting to update the variable that controls the loop int years = 1; while (years <= 20) { double interest = balance * RATE / 100; balance = balance + interest; }  Example: incrementing instead of decrementing int years = 20; while (years > 0) { double interest = balance * RATE / 100; balance = balance + interest; years++; }  These loops run forever – must kill program

Copyright © 2014 by John Wiley & Sons. All rights reserved.55 Problem Solving: Hand-Tracing  A simulation of code execution in which you step through instructions and track the values of the variables.  What value is displayed? 1int n = 1729; 2int sum = 0; 3while (n > 0) 4{4{ 5 int digit = n % 10; 6 sum = sum + digit; 7 n = n / 10; 8}8} 9System.out.println(sum);

Copyright © 2014 by John Wiley & Sons. All rights reserved.56 Problem Solving: Hand-Tracing - Step by Step  Step 1  Step 2

Copyright © 2014 by John Wiley & Sons. All rights reserved.57 Problem Solving: Hand-Tracing - Step by Step  Step 3

Copyright © 2014 by John Wiley & Sons. All rights reserved.58 Problem Solving: Hand-Tracing - Step by Step  Step 4

Copyright © 2014 by John Wiley & Sons. All rights reserved.59 Problem Solving: Hand-Tracing - Step by Step  Step 5

Copyright © 2014 by John Wiley & Sons. All rights reserved.60 Problem Solving: Hand-Tracing - Step by Step  Step 6

Copyright © 2014 by John Wiley & Sons. All rights reserved.61 Problem Solving: Hand-Tracing - Step by Step  Step 7

Copyright © 2014 by John Wiley & Sons. All rights reserved.62 Problem Solving: Hand-Tracing - Step by Step  Step 8

Copyright © 2014 by John Wiley & Sons. All rights reserved.63 Problem Solving: Hand-Tracing - Step by Step  Step 9  Step 10 The sum, which is 19, is printed