Control Structures: if and while A C S - 1903 L E C T U R E 4
Control structures 3 constructs are essential building blocks for programs Sequences compound statement Decisions if, switch, conditional operator Loops while, do while, for, enhanced for (later)
Compound statement A compound statement is often used with ifs, whiles etc. to provide a group of statements to be executed repeatedly or conditionally. opening brace closing brace { } temp = x; x = y; y = temp;
Decision structures : the if statement An if statement is coded with a logical expression and either one statement (statement) or two statements (statement 1 and statement 2 ) if (logical expression) statement 1 else statement The else clause is optional 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.
Logical expressions if (logical expression)... 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: a < b a < b b < c a+5 >= q*3 found && i<100 a == b i < 100 && j < 100 a!= b!found && i < 100 found! found
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 execution of program statements continue at the statement following the if; when the expression evaluates to false, statement 2 executes execution of program statements continue at the statement following the if.
Example 1 Get a number from the user and display 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"); } Indented code this is practice we will follow PositiveOrNot.java Only one of these can execute
Example 2 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 greater than 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. 16 is greater than 9 and so the sum of its digits is calculated 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
Example 2 import java.util.scanner; TestGreaterThanNine.java 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); The else clause is not necessary; omitted
Nested ifs statement 1 or statement 2 can be any Java statement statement 1, statement 2 can be ifs or other control structures We can nest one control structure inside another control structure
Nested ifs: example 1 Suppose we must handle a purchase transaction in one of two ways: 1. If the customer pays cash we must round up/down as there are no pennies. 2. If the customers pays by electronic means there is a surcharge of 25 cents.
Nested ifs: example 1 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 Steps 2 and 3 can be handled with an if-else can be handled with a nested if-else
Nested ifs: example 1 RoundCostUpDown.java if (typepayment.equals("cash")) { if (originalcost % 5 < 3) actualcost = originalcost - originalcost%5; else actualcost = originalcost + (5 - originalcost%5); } else actualcost = originalcost + 25; Note the indentation Nested if to handle rounding for a cash payment
Nested ifs: example 2 A table for converting alphabetic grades to a numeric value: Letter grade Numeric grade A 4 B 3 C 2 D 1 F 0 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
Nested ifs: example 2 To program this conversion, nested ifs are useful Letter grade Numeric grade A 4 B 3 C 2 D 1 F 0 We can structure this code in many ways We will consider 3 ways to write the logic
Option 1 LetterGradeToNumericGrade1.java 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 - e.g. when the grade is A the other ifs do not need to execute, but they do
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 LetterGradeToNumericGrade2.java
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; IfElseIfIndentation.java Due to the similarity of the logical conditions, this style is favourable - shows the choices at the same level of indentation
Loops: while while statement executes a statement as long as some expression is true while (logical expression) statement Recall: A logical expression is an expression that evaluates true or false.
Recall: while How a while executes:
Loops: while E.g. display the digits from 0 to 9 Numbers0to9.java int count = 0; System.out.println("Numbers"); while ( count < 10 ){ System.out.println(count); count = count + 1; } Start of compound statement Executed repeatedly until count is 10 Indented code How can you modify this code to display numbers from 9 down to 0?
Loops: while E.g. display the digits of a positive number DisplayDigits.java while (number > 0){ int digit = number % 10; System.out.print("\t"+digit); number = number / 10; System.out.println("\t"+number); } Indented code Start of compound statement Executed repeatedly as long as number > 0 How can you modify this code to calculate the sum of an integer s digits?
Loops: nesting whiles A while can contain another while e.g. displaying a times table 1 2 3 4 1 1 2 3 4 2 2 4 6 8 3 3 6 9 12 4 4 8 12 16
Loops: nesting whiles To produce a times table, use one loop inside another. We say one loop is nested inside the other loop. To begin: 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 we want a listing like that shown on previous slide.
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" ); } } NestedWhiles.java For each value of i, j takes on values 1, 2, 3, 4 One while nested inside another while
Looping: nested whiles Output from nested whiles 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 Times table from class: TimesTableWhile.java
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
Autoincrement and autodecrement n++; m--; post-increment post-decrement ++n; --m; pre-increment pre-decrement
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.
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);