Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations."— Presentation transcript:

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

2 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

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

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

5 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

6 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: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

7 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

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

9 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

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

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

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

13 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

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

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

16 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

17 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

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

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

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

21 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 100-90A 80-89B 70-79C <70D Sample output:

22 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

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

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

25 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

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

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

28 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 } 1 1 2 2

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

30 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; }

31 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

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

33 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

34 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

35 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

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

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

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

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

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

41 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

42 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

43 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

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

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

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

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

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

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

50 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(); }

51 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(); }

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

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

54 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

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

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

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

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

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

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

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

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

63 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


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

Similar presentations


Ads by Google