Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional.

Similar presentations


Presentation on theme: "1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional."— Presentation transcript:

1 1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional operator Loops  while, do while, for, enhanced for Loops often use a programming idiom called autoincrement and autodecrement.

2 2 Control Structures Order of topics: compound while autoincrement and autodecrement if for do-while

3 3 Compound statement A compound statement is a group of statements that are executed sequentially, one following the other, from beginning to end { temp = x; x = y; y = temp; } Opening brace Closing brace A compound statement is often used with if’s, while’s etc. … to provide a group of statements to be executed repeatedly or conditionally.

4 4 Loops: while While statement executes a statement as long as some expression is true while ( logical expression ) statement

5 5 Loops: while How a while executes

6 6 Loops: while A logical expression is an expression that evaluates true or false. Suppose a, b, q, i, j are integers and found is boolean. Examples of logical expressions: while ( logical expression ) statement a < b a+5 >= q*3 a == b a != b found a < b || b < c found && i<100 i < 100 && j < 100 !found && i < 100 ! found

7 7 Loops: while Example 1 Page 70. Numbers0to9 displays the digits from 0 to 9 A code snippet: int count = 0; System.out.println("Numbers"); while ( count < 10 ){ System.out.println(count); count = count + 1; } Indented code Executed repeatedly until count is 10 Start of compound statement How can you modify this code to display numbers from 9 down to 0?

8 8 Loops: while Example 2 Page 72. DisplayDigits displays the digits of a positive number. A code snippet: while (number > 0){ int digit = number % 10; System.out.print("\t"+digit); number = number / 10; System.out.println("\t"+number); } Indented code Executed repeatedly as long as number > 0 Start of compound statement How can you modify this code to calculate the sum of an integer’s digits?

9 9 Loops: Nesting whiles A while can contain another while Example. Suppose we need to display a times table (See example 3 page 72) 1234 11234 22468 336912 4481216

10 10 Loops: Nesting whiles To produce a times table its best to use one loop inside another. We say one loop is nested inside the other loop. To begin with we will just produce a simple vertical listing of i, j, i*j where i varies from 1 to 4 and j varies from 1 to 4. Ultimately one wants a listing like that shown on previous slide. see Example 3 on page 74 … shown on next slide see Exercise 14 on page 77

11 11 Loops: Nesting whiles public class NestedWhiles { public static void main(String[] args) { int i, j; System.out.println("\ti\tj\ti*j"); // i takes on values 1,2,3,4 i = 1; while (i < 5){ j = 1; // j takes on values 1,2,3,4 while (j < 5){ System.out.println("\t"+i+"\t"+j+"\t"+(i*j)); j = j + 1; } i = i + 1; } System.out.println("program ended"); } a while nested inside another while For each value of i, j takes on values 1, 2, 3, 4

12 12 Loops: Nesting whiles Output from NestedWhiles Heading Note when i is 1 j takes on 1, 2, 3, 4 when i is 2 j takes on 1, 2, 3, 4 when i is 3 j takes on 1, 2, 3, 4 when i is 4 j takes on 1, 2, 3, 4

13 13 Loops and Autoincrement, Autodecrement statements such as n = n + 1; m = m - 1; are so common in programming that languages such as Java include special operators for this purpose called autoincrement and autodecrement

14 14 Autoincrement and Autodecrement n++; m--; and ++ n; --m; post-increment post-decrement pre-increment pre-decrement

15 15 Autoincrement and Autodecrement n++; ++ n; m--; --m; When autoincrement is used alone and not as part of a larger expression pre- and post- increment have the same effect … to increment the operand by 1. Similarily …. When autodecrement is used alone and not as part of a larger expression pre- and post- decrement have the same effect … to decrement the operand by 1.

16 16 ASIDE: for Autoincrement and Autodecrement ASIDE: autoincrement, autodecrement within an expression… post-increment and post-decrement: the operand’s value is used and then the operand’s value is incremented/ decremented pre-increment and pre-decrement: the operand’s value is incremented/ decremented and then the operand’s value is used // try this out // what is printed? int m = 1; int n = m++ + m++; System.out.println("m="+m); System.out.println("n="+n); // try this out // what is printed? int m = 1; int n = ++m + ++m; System.out.println("m="+m); System.out.println("n="+n);

17 17 Decision structures : the if statement An if statement is coded with a logical expression and either one statement (statement 1 ) or two statements (statement 1, statement 2 ) written according to syntax as: if ( logical expression) statement 1 else statement 2 We say the if is a decision structure … based on the outcome of evaluating the logical expression one of possibly two statements is executed. The else clause is optional

18 18 Decision structures : the if statement if ( logical expression) statement 1 else statement 2 When an if executes the logical expression is evaluated and : when the expression evaluates to true statement 1 executes, and then execution of program statements continue at the statement following the if ; when the logical expression evaluates to false statement 2 executes, and then execution of program statements continue at the statement following the if. The else clause is optional

19 19 Decision structures : the if statement Example. PositiveOrNot page 79 Gets a number from the user and displays positive or not positive accordingly int number = keyboard.nextInt(); System.out.print("the number "+number+" is "); // Display a message if number is positive or not if (number > 0) { System.out.println("positive"); } else { System.out.println("not positive"); } Only one of these can execute Strictly speaking, the { } are not required when there is just a single statement … but it is a common practice to always use compound statements in control structures.

20 20 Decision structures : the if statement Another example: Background: The Canadian SIN can be tested for a proper check digit. Part of the process involves multiplying individual digits by either 1 or 2. When a digit is multiplied by 2 and the result is > 9 then the two digits of this product must be added. For example, if the digit is 8 then the product 2*8 is 16 … the sum of its digits is  1+6 is 7 Along these lines consider a simpler program that: 1.gets a digit from the user 2.multiplies that digit by 2 3.if the product is <= 9 then displays the digit otherwise displays the sum of the digits of the product

21 21 Decision structures : the if statement import java.util.Scanner; /** * Get a digit from the user and multiply by 2 * If the result is larger than 9 add its two digits */ public class TestGreaterThanNine { public static void main(String[] args) { Scanner kb = new Scanner(System.in); System.out.println("Please enter a single digit:"); int digit = kb.nextInt(); int result = digit*2; if (result > 9) { result = result/10 + result%10; } System.out.println(" result is "+result); } else clause is not necessary… and so omitted

22 22 Decision structures : nested ifs statement 1 or statement 2 can be any Java statement statement 1, statement 2 can be ifs, whiles, etc. We can nest one control structure inside another control structure

23 23 Decision structures : nested ifs Example. Round Cost Up Down pages 82-83 Suppose we must handle a purchase transaction in one of two ways: If the customer pays cash we must round up/down as there are no pennies. If the customers pays by electronic means there is a surcharge of 25 cents.

24 24 Decision structures : nested ifs In pseudocode: 1.obtain the type and amount of the purchase 2.if the purchase is cash then round the cost up/down 3.otherwise add on the surcharge 4.display the total cost for the customer Code for this is shown on next slide  This can be handled with a nested if-else

25 25 Decision structures : the if statement if (typePayment.equals("cash")) { if (originalCost % 5 < 3) actualCost = originalCost - originalCost%5; else actualCost = originalCost + (5 - originalCost%5); } else actualCost = originalCost + 25; Nested if to handle the details of the cash payment

26 26 Decision structures : nested ifs Example. Consider the example beginning on page 84 A table for converting alphabetic grades to a numeric value: When you need to convert some letter grade to its equivalent numeric value you would look for which row the letter appears in and read off the numeric value in that same row. E.g. the numeric value corresponding to B is 3 Letter gradeNumeric grade A4 B3 C2 D1 F0

27 27 Decision structures : nested ifs To program this conversion nested ifs are useful We can structure this code in many ways We will consider three ways to write the required logic  Letter gradeNumeric grade A4 B3 C2 D1 F0

28 28 Decision structures : nested ifs Option 1: if (letterGrade.equals("A")) numericGrade = 4.0; if (letterGrade.equals("B")) numericGrade = 3.0; if (letterGrade.equals("C")) numericGrade = 2.0; if (letterGrade.equals("D")) numericGrade = 1.0; This style requires the evaluation of expressions that would not be necessary (for example, when the grade is A the other if s do not need to execute, but they do)

29 29 Decision structures : nested ifs Option 2: if (letterGrade.equals("A")) numericGrade = 4.0; else if (letterGrade.equals("B")) numericGrade = 3.0; else if (letterGrade.equals("C")) numericGrade = 2.0; else if (letterGrade.equals("D")) numericGrade = 1.0; else numericGrade = 0.0; This style uses indentation properly … each if is indented within the outer if … but the code easily goes off the page/screen and gets hard to read

30 30 Decision structures : nested ifs Option 3: if (letterGrade.equals("A")) numericGrade = 4.0; else if (letterGrade.equals("B")) numericGrade = 3.0; else if (letterGrade.equals("C")) numericGrade = 2.0; else if (letterGrade.equals("D")) numericGrade = 1.0; else numericGrade = 0.0; Due to the similarity of the logical conditions, this style would be favoured by many … it shows the choices at the same level of indentation

31 31 Loops: for The for statement is commonly used where there is a need for a statement to be executed a specific number of times The syntax of the for statement we consider here is for ( initialization; logical expression; increment ) statement

32 32 Loops: for

33 33 Loops: for Example 1, Numbers0To9WithFor, uses a for to display integers 0 through 9 A code snippet: for (int count=0; count < 10; count++ ) System.out.println(count); Increment Count is increased by 1 each time through the loop Loop continues as long as count < 10 count starts at 0 The statement that is executed repeatedly This statement is indented for clarity and readability

34 34 Loops: for Example 2, GetIndividualCharacters, uses charAt and a for. Displays characters one-by-one. A code snippet: String text = "abc123"; int textLength = text.length(); System.out.println("text string is: "+text); System.out.println("now, each character one-by-one"); for (int i=0; i<textLength; i++){ char c = text.charAt(i); System.out.println(c); } Length of the string length used to control number of times loop executes Get the i th character Indented code

35 35 Loops: nesting control structures Example 3, CountLetters, uses an if and a for. Counts the number of times the letter ‘a’ appears. A code snippet: text = kb.nextLine(); int count = 0; for (int i=0; i<text.length(); i++){ if (text.charAt(i) == 'a') count++; } System.out.println("The line contains "+count +" a\'s"); A line of text length used to control number of times loop executes Use an if to test the i th character

36 36 Loops: nesting control structures Example 4, NestedFor, uses two for s, one nested inside the other Lines 10 to 13 …. the outer for Lines 11 and 12 … the inner for 10 for (int i =1; i <=4; i ++) { 11 for (int j =1; j <=4; j ++) 12 System.out.println "\t"+i+"\t"+j+"\t"+(i*j)); 13 } How many times does this execute? The outer for contains a compound statement

37 37 Loops: do-while The do-while statement is useful when it is known the loop body must execute at least once. syntax : do statement while ( logical expression ) ;

38 38 Loops: do-while

39 39 Loops: do-while The do-while statement is useful when it is known the loop body must execute at least once. syntax : do statement while ( logical expression ) ;

40 40 Loops: do-while Example. Suppose we are adding the digits of a positive integer There must be at least one digit to add to a total  can use do-while System.out.println("Enter a number"); int n = kb.nextInt(); int sum = 0; do { sum += n % 10; n /= 10; } while (n>0); System.out.println("sum is "+sum); Executed at least once How many times does the loop execute if n is 5? 25? 0?


Download ppt "1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional."

Similar presentations


Ads by Google