Introduction to Computer Science, Shimon Schocken, IDC Herzliya Lectures 3.1 3.2 Control Structures Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 1 Control structures A program is a sequence of statements. On the right we see the same program, in two separate runs In each run some statements execute (the underlined ones); the other statements are skipped In order to affect such different flows of execution, we need programming mechanisms that tell the computer to branch to different code segments. Run(input1) s0 s0 s1 s1 s2 s2 s3 s3 s4 s4 s5 s5 s6 s6 s7 s7 s8 s8 s9 s9...... Run(input2) s0 s0 s1 s1 s2 s2 s3 s3 s4 s4 s5 s5 s6 s6 s7 s7 s8 s8 s9 s9...... Low level programming languages affect branching using GOTO statements High level programming languages affect branching using high-level abstractions like IF, WHILE, SWITCH, and so on Taken together, these statements are called control structures. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 2
Control structures: lecture outline Boolean expressions and variables The IF statement The conditional The WHILE statement The SWITCH statement The DO statement The FOR statement Shorthand operators Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 3 The IF statement (example) import import java.util.scanner; class class AgeCheck AgeCheck { static static final final int int AGELIMIT AGELIMIT = 18; 18; public public static static void void main(string[] args) args) { Scanner Scanner scan scan = new new Scanner(System.in); System.out.println("Enter your your age:"); age:"); int int age age = scan.nextint(); if if (age (age < AGELIMIT) AGELIMIT) System.out.println("Sorry, " + age age + " is is under under the the allowed allowed age."); age."); // // Code Code continues continues...... The body of the IF can be either a single statement or a a block of statements: if if (age (age < AGELIMIT) AGELIMIT) { System.out.println("Sorry, " + age age + " is is under under the the allowed allowed age."); age."); System.out.println("Try again again when when you you are are old old enough."); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 4
The IF statement Syntax: if if (condition) statement statement condition statement IF: the most basic branching mechanism The condition s value determines which branch to take Condition: a Boolean expression that evaluates to either TRUE or FALSE. Syntax convention: Throughout the slides in this lecture, statement stands for either a single statement or a block of statements, grouped by curly brackets. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 5 The IF / ELSE statement (example) import import java.util.scanner; class class AgeCheck2 AgeCheck2 { static static final final int int AGELIMIT AGELIMIT = 18; 18; public public static static void void main(string[] args) args) { Scanner Scanner scan scan = new new Scanner(System.in); System.out.println("Enter your your age:"); age:"); int int age age = scan.nextint(); if if (age (age < AGELIMIT) AGELIMIT) System.out.println("Sorry, you you are are under under the the allowed allowed age."); age."); else else { System.out.println("Welcome! Wait Wait while while the the game game is is loading loading...");..."); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 6
The IF / ELSE statement Syntax: if if (condition) statement1 statement1 else else statement2 statement2 statement1 condition statement2 Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 7 Nested IF (example 1) System.out.println("Enter your your age:"); age:"); int int age age = scan.nextint(); if if (age (age < AGELIMIT) AGELIMIT) System.out.println("Sorry, you you are are under under the the allowed allowed age."); age."); else else { System.out.println("Enter your your credit credit card:"); card:"); int int cardnumber = scan.nextint(); if if (cardnumber > 0) 0) // // (simulating a more more elaborate elaborate CC CC test) test) System.out.println("Welcome!...");..."); else else System.out.println("Sorry, bad bad card"); card"); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 8
Nested IF (example 2) // // Reads Reads two two integers integers and and compares compares them them import import java.util.scanner; class class Compare2Numbers { public public static static void void main(string[] args) args) { Scanner Scanner scan scan = new new Scanner(System.in); System.out.print("Enter a number:"); int int a = scan.nextint(); System.out.print("Enter another another number"); number"); int int b = scan.nextint(); if if (a (a!=!= b) b) if if (a (a > b) b) System.out.println(a + " is is greater"); else else System.out.println(b + " is is greater"); else else System.out.println("the numbers numbers are are equal"); equal"); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 9 Nested IF Syntax: if if (condition1) if if (condition2) statement statement if if (condition1) statement1 statement1 else else if if (condition2) statement2 statement2 if if (condition1) statement1 statement1 else else if if (condition2) statement2 statement2 else else if if (condition3) statement3 statement3 // // etc. etc. The nesting can go as deep as you want Use with caution: telescoped code is hard to read and comprehend. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 10
Example: using IF to validate inputs Whenever we request a user to enter some input, we must assume that an invalid value can be entered Valid / invalid: according to the application s requirements. System.out.println("Enter number number of of items:") items:") int int n = scan.nextint(); if if (n (n < 0) 0) { System.out.println("Number of of items items must must be be positive!"); else else { double double total total = n * ITEM_PRICE; System.out.println("The total total price price is:" is:" + total); total); This code is asking for trouble. Can you see why? Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 11 Control structures: lecture outline Boolean expressions and variables The IF statement The conditional The WHILE statement The SWITCH statement The DO statement The FOR statement Shorthand operators Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 12
Control structures are always based on evaluating some condition: if if ((age ((age > 18) 18) && && (city (city == == "LA")) "LA")) // // accept accept application condition Where do these conditions come from? Algorithmic needs Requirements analysis We We accept accept applications applications from from LA LA residents residents older older than than 18 18 Continue Continue the the loop loop until until Math.abs(r-x*x) < < epsilon epsilon If If the the package package weights weights more more than than 10 10 kg kg or or the the shipping shipping distance distance is is more more than than 100 100 km km we we charge charge 10% 10% extra extra (ambiguous (ambiguous ) ) Three Three numbers numbers x, x, y, y, z are are said said to to be be Pythagorean if if x 2 2 + + yy 2 2 = = z 2 2 Such statements can be expressed in computer programs as Boolean expressions. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 13 Boolean expressions We accept applications from LA residents older than 18 if if ((age ((age > 18) 18) && && (city (city == == "LA")) "LA")) // // accept accept application condition Boolean expressions anatomy: (age > 18) && && (city == == "LA") George Boole, 1815-1864 ( A Calculus of Logic ) Relational operator Boolean operator Relational operator Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 14
Relational operators Operator ==!= < <= > >= Meaning equal to not equal to less than less than or equal to greater than greater than or equal to Examples: age age > 18 18 city city == == "LA" "LA" x!=!= 100 100 gpa gpa <= <= 3.75 3.75 Each operator operates on two operands Called relational operators since they test how the operands relate to each other Return a Boolean value. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 15 Logical (Boolean) operators Boolean expressions can be combined using logical operators Java offers three logical operators: Operator! && Operation Logical NOT Logical AND Logical OR Each operator takes a Boolean operand and returns a Boolean result Logical NOT is unary (takes one operand); Logical AND and logical OR are binary (two operands). Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 16
Truth tables NOT (!) a!a Boolean expressions are functions taking inputs and returning outputs A truth table shows the output of the Boolean expression for every possible input The truth table can be viewed as the definition of the logical operator. AND (&&) OR ( ) a b a && b a b a b!a is if a is and otherwise (a && b) is if both a and b are and otherwise (a b) is if either a or b or both are and otherwise. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 17 Complex Boolean expressions Boolean expressions can be combined using logical operators, creating more complex expressions: if if (a<1 (a<1 a%2!=0) a%2!=0) System.out.println("The input input must must be be a positive positive even even number!"); The result of any Boolean expression can be calculated using a truth table: a<1 a%2!= 0 a<1 a%2=0 Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 18
Boolean variables Boolean expressions can be assigned to Boolean variables: // // x must must be be between between 0 and and 100 100 boolean boolean b, b, c; c; b = (x (x >= >= 0); 0); // // if if x >= >= 0 c = b && && (x (x <= <= 100); 100); // // if if (x (x >= >= 0) 0) AND AND (x (x <= <= 100) 100) if if (c) (c) System.out.println("x is is in in range"); range"); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 19 Example // // Determines if if a given given triangle triangle is is right. right. class class RightTriangle { public public static static void void main(string[] args) args) { // // Get Get the the triangle s three three edges edges a,b,c a,b,c (omitted) (omitted) boolean boolean righttriangle = (a*a (a*a + b*b b*b == == c*c) c*c) (a*a (a*a + c*c c*c == == b*b) b*b) (b*b (b*b + c*c c*c == == a*a); a*a); if if (righttriangle) System.out.println("It s a right right triangle"); else else System.out.println("It s not not a right right triangle"); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 20
The conditional operator: a shorthand IF/ELSE mechanism Example int int max max = (a (a > b) b)? a : b; b; Syntax condition condition? expression1 : expression2 ; The conditional is a ternary operator, requiring 3 operands Similar to an IF/ELSE statement; However, the conditional is not a statement, but an expression that returns a value If the condition is, the expression returns the value of expression1; else, the expression returns the value of expression2; Example Systems.out.println("Thanks! you you bought bought + count count + ((count==1)? "item" "item" : "items"); "items"); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 21 Control structures: lecture outline Boolean expressions and variables The IF statement The conditional The WHILE statement The SWITCH statement The DO statement The FOR statement Shorthand operators Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 22
The WHILE statement Syntax: while while (condition) statement statement condition statement A while loop executes zero or more times. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 23 Example: counting...... // // Counts Counts from from 1 to to n. n. System.out.print("Enter a number"); number"); n = scan.nextint(); int int count count = 1; 1; while while (count (count <= <= n) n) { System.out.println(count); count count = count count + 1; 1; System.out.println("done");...... Simulate the program: What will the program print when... n = 5 n = 1 n = 0 n = -3. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 24
Example: factors...... // // Gets Gets an an integer integer and and prints prints its its factors factors System.out.print("Enter a number"); number"); n = scan.nextint(); System.out.println("The divisors divisors of of " + n + " are:"); are:"); int int i = 1; 1; while while (i (i <= <= n) n) { if if (n (n % i == == 0) 0) System.out.println(i); i = i + 1; 1; Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 25 Using WHILE to validate inputs // // Get Get the the number number of of items items and and make make sure sure it s it s non-negative System.out.print("Enter number number of of items:") items:") int int n = scan.nextint(); while while (n (n <= <= 0) 0) { System.out.println("Number of of items items must must be be positive!"); System.out.print("Enter number number of of items:") items:") int int n = scan.nextint(); System.out.println("The total total price price is:" is:" + (n (n * ITEM_PRICE)); This code is bullet-proof : there is no way to enter an invalid input. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 26
PalindromeTester radar kayak import import java.util.scanner; drab bard able was I ere I saw elba public public class class PalindromeTester { public public static static void void main main (String[] (String[] args) args) { Dennis and Edna sinned Rise to vote, sir Scanner Scanner scan scan = new new Scanner Scanner (System.in); Doom an evil deed, liven a mood System.out.print("Enter some some text: text: "); "); String String txt txt = scan.nextline(); Go hang a salami; I m a lasagna hog A man, a plan, a canal, Panama int int left left = 0; 0; int int right right = txt.length() - 1; 1; while while (str.charat(left) == == str.charat(right) && && left left < right) right) { left++; left++; right--; right--; if if (left (left < right) right) System.out.println ("The ("The text text is is NOT NOT a palindrome."); else else System.out.println ("The ("The text text IS IS a palindrome."); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 27 Control structures: lecture outline Boolean expressions and variables The IF statement The conditional The WHILE statement The SWITCH statement The DO statement The FOR statement Shorthand operators Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 28
The SWITCH statement Syntax switch switchexpression { case casevalue1 : statement1 statement1 case casevalue2 : statement2 statement2..... default default : statement statement statementi refers to one or more statements The default part is optional The expression value is compared to each case value; if there is a match, the corresponding statement is executed If none of the values matches, the default statement is executed The expression and the values must be integral values, e.g. either integer or character. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 29 SWITCH Example import import java.util.scanner; // // ATM ATM user user selection selection logic logic public public class class ATMlogic ATMlogic { public public static static final final int int VIEW_BALANCE = 1; 1; public public static static final final int int VIEW_SAVINGS = 2; 2; public public static static final final int int CASH_TRANSFER = 3; 3; // //...... // // Inside Inside the the program s program s main main loop: loop: Scanner Scanner scan scan = new new Scanner(System.in); System.out.print("Enter your your choice:"); int int option option = scan.nextint(); BREAK can be used to shortcut execution and transfer control to the end of the SWITCH SWITCH is equivalent to a nested IF/ELSE. switch switch (option) (option) { case case VIEW_BALANCE: showbalance(); break; break; case case VIEW_SAVINGS: showsavings(); break; break; // // Etc. Etc. default: default: System.out.println( No such such option! );...... Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 30
Control structures: lecture outline Boolean expressions and variables The IF statement The conditional The WHILE statement The SWITCH statement The DO statement The FOR statement Shorthand operators Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 31 The DO statement Syntax: do do statement statement while while (condition); statement condition Similar to WHILE, except that the condition evaluates at the end of the loop WHILE loop executes 0 or more times DO loop executes 1 or more times. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 32
Example: powers of 2 import import java.util.scanner; // // Prints Prints the the powers powers of of 2 up up to to a limit limit class class PowerOf2V1 { public public static static void void main(string[] args) args) { Scanner Scanner scan scan = new new Scanner(System.in); System.out.print("Enter a number:"); int int limit limit = scan.nextint(); int int n = 1; 1; do do { n = n * 2; 2; System.out.println("Next power power of of 2: 2: " + n); n); while while (n (n <= <= limit); limit); What happens if the user enters 1? Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 33 The FOR statement Syntax: for for ( initialization ; condition condition ; increment increment ) statement; statement; Equivalent to: initialization while whilecondition { statement; statement; increment; increment; Many loops have this common pattern Comes to play when the number of iterations is known in advance initialization Example: condition for for (int (int count=0; count=0; count count <= <= 75; 75; count++) count++) { System.out.println (count); (count); statement increment Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 34
Example: powers of 2 Prints the powers of 2 up to a limit for(int for(int n = 1 ; n <= <= limit limit ; n = n * 2) 2) { System.out.println("Next power power of of 2: 2: " + n); n); Equivalent to: do do { n = n * 2; 2; System.out.println("Next power power of of 2: 2: " + n); n); while while (n (n <= <= limit); limit); FOR can yield tighter code; better handling of control variables. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 35 Omitting parts of the FOR statement FOR loop without initialization for for ( ; condition condition ; increment increment ) statement; statement; Any one of the three expressions in the FOR header is optional The two semicolons are always required. FOR loop without increment: for for ( initialization; condition condition ; ) statement; statement; Infinite FOR loop: for for ( initialization; ;increment ) statement; statement; Examples: for for (;;) (;;) { // // an an infinite infinite loop loop System.out.println ("beep"); ("beep"); for for (; (; count count < max max ; count count ++ ++ ) { System.out.println (count); (count); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 36
Example: Multiplication table // // 10 10 by by 10 10 multiplication table table class class MultiplicationTable { public public static static void void main(string[] args) args) { for(int for(int j=1 j=1 ; j <= <= 10 10 ; j++) j++) { for(int for(int k=1 k=1 ; k <= <= 10 10 ; k++) k++) System.out.print(j*k); System.out.println(); Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 37 BREAK and CONTINUE BREAK can be used to terminate a loop; Execution continues after the loop s end CONTINUE can be used to terminates the current iteration; Execution continues by evaluating the loop s condition // // Reads Reads a a series series of of positive positive numbers numbers from from the the user, user, until until // // 0 0 is is read. read. Computes Computes and and prints prints the the series' series' average. average. class class Average Average { { public public static static void void main(string[] main(string[] args){ args){ Scanner Scanner scan scan = = new new Scanner(System.in); Scanner(System.in); double double x, x, sum sum = = 0; 0; count count = = 0; 0; while() while() { { System.out.print("Enter System.out.print("Enter a a positive positive number: ); number: ); x x = = scan.nextin(); scan.nextin(); if if (x (x == == 0) 0) break; break; if if (x (x < < 0) 0) { { System.out.println( Only System.out.println( Only positive positive numbers! ); numbers! ); continue; continue; sum sum += += x x ; ; count count ++ ++ ; ; System.out.println( The System.out.println( The average average is is +sum/count); +sum/count); Ugly code... Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 38
Control structures: lecture outline Boolean expressions and variables The IF statement The conditional The WHILE statement The SWITCH statement The DO statement The FOR statement Shorthand operators Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 39 Increment / decrement operators k ++ ++ Is equivalent to k = k + 1 k -- -- Is equivalent to k = k - 1 k must be a numeric variable. Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 40
Prefix / postfix notation: k ++ ++ Has the same impact on count as ++ ++ k Prefix: the operator is written before the operands Postfix: the operators is written after the operands When used in the context of larger expression, the prefix / postfix notations make a difference: n = k ++ ++ Is not the same as n = ++ ++ k The rules of the game: Expressions count++ ++count count-- --count Operation add 1 add 1 subtract 1 subtract 1 Value Of expression old value new value old value new value Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 41 Examples count count = 30 30 total total = count++ count++ // // now now count=31 count=31 and and total=30 total=30 count count = 30 30 total total = ++count ++count // // now now count=31 count=31 and and total=31 total=31 sum sum = 50 50 System.out.println(sum +" +" "+ "+ sum++ sum++ +" +" "+ "+ ++sum ++sum +" +" "+ "+ sum sum +" +" "+ "+ sum-- sum-- +" +" "+ "+ sum) sum) What will it print? Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 42
Assignment operators Often we perform an operation on a variable, and then assign the result to the same variable. Example: sum = + x sum sum = + x is equivalent to: sum sum += += x The rules of the game: Operator += -= *= /= %= Example x+=y x-=y x*=y x/=y x%=y Equivalent to x = x + y x = x - y x = x * y x = x / y x = x % y The right hand side, which can be a complex expression, is evaluated first, and then combined with the rest of the assignment: x /= /= x - y is equivalent to: x = x / (x (x - y) y) Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 43