Presentation is loading. Please wait.

Presentation is loading. Please wait.

Unit 3 1 Flow of control H We will talk about: conditional statements  if-then-else  logical and conditional operators  switch repetition statements.

Similar presentations


Presentation on theme: "Unit 3 1 Flow of control H We will talk about: conditional statements  if-then-else  logical and conditional operators  switch repetition statements."— Presentation transcript:

1 unit 3 1 Flow of control H We will talk about: conditional statements  if-then-else  logical and conditional operators  switch repetition statements  while  do  for basic programming concepts object oriented programming topics in computer science syllabus

2 unit 3 2 Flow of Control H Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written H Some programming statements modify that order, allowing us to: decide whether or not to execute a particular statement, or perform a statement over and over repetitively H The order of statement execution is called the flow of control

3 unit 3 3 Conditional Statements H A conditional statement lets us choose which statement will be executed next; therefore they are sometimes called selection statements H Conditional statements give us the power to make basic decisions H Java's conditional statements are the if statement, the if-else statement, and the switch statement

4 unit 3 4 The if Statement H The if statement has the following syntax: if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed. If it is false, the statement is skipped.

5 unit 3 5 Logic of an if statement condition evaluated false statement true SimpleIf

6 unit 3 6 Example - class Temperature class Temperature { static final int THRESHOLD = 27; public static void main(String[] args) { System.out.println(“Enter temperature:”); int temperature = EasyInput.readInt(); System.out.println(“Current temperature “+ temperature); if (temperature > THRESHOLD) System.out.println(“It’s hot in here!”); } }

7 unit 3 7 Conditions via Boolean Expressions  The condition of an if statement must evaluate to a true or false result H Booleas values (true/false) are obtained by relational operators: H In relational operators the operands are numbers, the result is boolean Operator == != < <= > >= Meaning equal to not equal to less than less than or equal to greater than greater than or equal to

8 unit 3 8 Block Statements H Several statements can be grouped together into a block statement H Blocks are delimited by braces H A block statement can be used wherever a statement is called for in the Java syntax

9 unit 3 9 Example – class Temperature2 class Temperature2 { static final int THRESHOLD = 27; public static void main(String[] args) { System.out.println(“Enter temperature:”); int temperature = EasyInput.readInt(); System.out.println(“Current temperature “+ temperature); if (temperature > THRESHOLD) { System.out.println(“It’s hot in here!”); System.out.println(“But we’ll survive.”); }

10 unit 3 10 Block Statements Q: assembly languages do not have blocks; what do they do instead?

11 unit 3 11 If.. Else Statement  An else clause can be added to an if statement to make it an if-else statement: if (condition) statement1; else statement2; H If the condition is true, statement1 is executed; if the condition is false, statement2 is executed

12 unit 3 12 Logic of an if-else statement condition evaluated statement1 true false statement2

13 unit 3 13 Example – class Temperature3 class Temperature3 { static final int FREEZING_POINT = 0; public static void main(String[] args) { System.out.println (“Enter temperature:”); int temperature = EasyInput.readInt(); if (temperature <= FREEZING_POINT) System.out.println(“It’s freezing!”); else System.out.println(“Above freezing.”); } }

14 unit 3 14 Example – class RightTriangle // Receives the length of the edges of a triangle // and determine if this is a right triangle class RightTriangle { public static void main(String[] args) { double a = EasyInput.readDouble(“Edge1:”); double b = EasyInput.readDouble(“Edge2:”); double c = EasyInput.readDouble(“Hypotenuse:”); boolean test = a*a+b*b == c*c; if (test) System.out.println(“It’s a right triangle”); else System.out.println( “It’s not a right triangle.”); } }

15 unit 3 15 Example: handling invalid input int numberOfItems = EasyInput.readInt (“Enter number of items:”); if (numberOfItems < 0) { System.out.println( “Number of items must be positive!”); } else { double price = numberOfItems * ITEM_PRICE; System.out.println(“The total price is:“ +price); }

16 unit 3 16 How to specify the condition simple if command: if ( condition ) statement1; else statement2; The condition is determined via logical operators logical operators operate on boolean variables, rather than numbers

17 unit 3 17 Logical Operators H There are three logical operators in Java: H They all take boolean operands and produce boolean results H Logical NOT is unary (one operand), but logical AND and OR are binary (two operands) Operator ! && || Operation Logical NOT Logical AND Logical OR

18 unit 3 18 Logical NOT H The logical NOT is also called logical negation or logical complement  If a is true, !a is false; if a is false, then !a is true H Logical expressions can be shown using truth tables a false true !a true false

19 unit 3 19 Logical AND  The expression a && b is true if both a and b are true, and false otherwise H Truth tables show all possible combinations of all terms a false true b false true false true a && b false true

20 unit 3 20 Logical OR  The expression a || b is true if a or b or both are true, and false otherwise a false true b false true false true a || b false true

21 unit 3 21 A note about truth tables H Any truth table defines a logical function a false true b false true false true f(a,b) false true

22 unit 3 22 Logical Operators: what for? H Logical operators are used to form more complex logical expressions if (a<1 || a%2!=0) { System.out.println( “The input should be a positive “+ “even number!”); return; } H Logical operators have precedence relationships between themselves and other operators

23 unit 3 23 Logical Operators H Full expressions can be evaluated using truth tables (like any logical function): a < 1 false true a%2!=0 false true false true a<1 || a%2!=0 false true

24 unit 3 24 statement true condition2 evaluated Nested if statements IfAnd false condition1 evaluated true

25 unit 3 25 Example – class CompareExample // Receives 2 integers and compare them class CompareExample { public static void main(String[] args) { System.out.println (“First number:”); int a = EasyInput.readInt(); System.out.println (“Second number:”); int b = EasyInput.readInt(); if (a != b) if (a > b) System.out.println(a+” is greater”); else System.out.println(b+” is greater”); else System.out.println(“the numbers are equal”); } }

26 unit 3 26 A note about style H The statements within an if or if-else statement should always be put in a block statement; the previous example was written in a poor style H Use of block statements eliminates the confusion that can arise in the previous example (think of a longer code and many if-else statements) H Use of blocks can also avoid a type of semantic mistakes

27 unit 3 27 The switch Statement H The switch statement provides another means to decide which statement to execute next H The switch statement evaluates an expression, then attempts to match the result to one of several possible cases H Each case contains a value and a list of statements H The flow of control transfers to statement list associated with the first value that matches

28 unit 3 28 The switch Statement H The general syntax of a switch statement is: switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 default:... }switchandcasearereservedwords If expression matches value2, control jumps to here

29 unit 3 29 The switch Statement H Often a break statement is used as the last statement in each case's statement list H A break statement causes control to transfer to the end of the switch statement H If a break statement is not used, the flow of control will continue into the next case H Sometimes this can be helpful, but usually we only want to execute the statements associated with one case

30 unit 3 30 The switch Statement H A switch statement can have an optional default case  The default case has no associated value and simply uses the reserved word default H If the default case is present, control will transfer to it if no other case value matches H Though the default case can be positioned anywhere in the switch, it is usually placed at the end H If there is no default case, and no other value matches, control falls through to the statement after the switch

31 unit 3 31 The switch Statement H The expression of a switch statement must result in an integral data type, like an integer or character; it cannot be a floating point value H Note that the implicit boolean condition in a switch statement is equality - it tries to match the expression with a value H You cannot perform relational checks with a switch statement

32 unit 3 32 The switch Statement // A client that enables you to connect to the // bank server and make remote banking operations... public class BankClient { public static final int VIEW_BALANCE = 1; public static final int VIEW_SAVINGS = 2; public static final int CASH_TRANSFER = 3; public static final int VIEW_LAST_OPERATIONS = 4; //...

33 unit 3 33 The switch Statement // Inside the main loop of the client: int option = EasyInput.readInt(“Enter your choice:”); switch(option) { case VIEW_BALANCE: showBalance(); break; case VIEW_SAVINGS: showSavings(); break; default: System.out.println(“No such option!”); }

34 unit 3 34 simple if command: if ( condition ) statement1; else statement2; The conditional operator is similar; but it is intended to select between different values, rather than between different actions

35 unit 3 35 The Conditional Operator H Java has a conditional operator that evaluates a boolean condition, determining which of two expressions is evaluated: condition ? expression1 : expression2 H If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated H expression1 and expression2 must return a value! H The result of the chosen expression is the result of the entire conditional operator

36 unit 3 36 The Conditional Operator H It is similar to an if-else statement, except that it is an expression that returns a value; for example: int max = (a > b) ? a : b;  If a is greater than b, then a is assigned to max ; otherwise, b is assigned to max H The conditional operator is ternary, meaning it requires three operands

37 unit 3 37 The Conditional Operator: example H System.out.println ("Your change is " + count + ((count == 1) ? "Dime" : "Dimes”)); input count is 1, program will print: Your change is 1 Dime input count is 10, program will print: Your change is 10 Dimes

38 unit 3 38 Flow of control H We will talk about: conditional statements  if-then-else  logical and conditional operators  switch repetition statements  while  do  for basic programming concepts object oriented programming topics in computer science syllabus

39 unit 3 39 Repetition Statements H Repetition statements allow us to execute a statement multiple times repetitively; they are often simply referred to as loops H Like conditional statements, they are controlled by boolean expressions H Java has three kinds of repetition statements: the while loop, the do loop, and the for loop; the programmer must choose the right kind of loop for the situation

40 unit 3 40 The while Statement H The while statement has the following syntax: while ( condition ) statement; while is a reserved word If the condition is true, the statement is executed. Then the condition is evaluated again. The statement is executed repetitively until the condition becomes false.

41 unit 3 41 Logic of a while loop statement true condition evaluated false FlowNestedIf

42 unit 3 42 The while statement  If the condition of a while statement is false initially, the statement is never executed; therefore, we say that a while statement executes zero or more times H As in the case of if, always use a block statement for the body of the while statement, even if it consists of only a single statement

43 unit 3 43 Example – class Counter // Counts from 1 to 5 class Counter { static final int LIMIT = 5; public static void main(String[] args) { int count = 1; while (count <= LIMIT) { System.out.println(count); count = count + 1; } System.out.println(“done”); } }

44 unit 3 44 Examples – class Factors // Gets an integer and prints its factors public static void main(String[] args) { int a = EasyInput.readInt(“Enter a number:”); int i = 1; System.out.println(“The divisors of “+a+” are:”); while(i <= a) { if (a%i == 0) { System.out.println(i); } i = i + 1; } }

45 unit 3 45 Example – class PowersOfTwo // Prints the first ten powers of two class PowersOfTwo { static final int LIMIT = 10; public static void main(String[] args) { int power = 1; int i = 1; while (i <= LIMIT) { power = power * 2; System.out.println(power); i = i + 1; } } }

46 unit 3 46 Infinite Loops  The body of a while loop must eventually make the condition false; if not, it is an infinite loop, which will execute until the user interrupts the program H This is a common type of logical error -- always double check that your loops will terminate normally

47 unit 3 47 Example – class Forever // This program contains an infinite loop class Forever { static final int LIMIT = 25; public static void main(String[] args) { int count = 1; <= while (count <= LIMIT) { System.out.println(count); count = count - 1; } } }

48 unit 3 48 The do Statement H The do statement has the following syntax: do { statement; } while ( condition ) Uses both the do and whilereservedwords The statement is executed once initially, then the condition is evaluated The statement is repetitively executed until the condition becomes false

49 unit 3 49 Logic of a do loop true condition evaluated statement false

50 unit 3 50 The do Statement H A do loop is similar to a while loop, except that the condition is evaluated after the body of the loop is executed H Therefore the body of a do loop will execute at least one time

51 unit 3 51 Comparing the while and do loops statement true condition evaluated false while loop true condition evaluated statement false do loop

52 unit 3 52 The for Statement H The for statement has the following syntax: for ( initialization ; condition ; increment ) statement;Reservedword The initialization portion is executed once before the loop begins The statement is executed until the condition becomes false The increment portion is executed at the end of each iteration

53 unit 3 53 The for Statement is equivalent to the following while loop: initialization; while ( condition ) { statement; increment; } for ( initialization ; condition ; increment ) statement;

54 unit 3 54 Logic of a for loop statement true condition evaluated false increment initialization

55 unit 3 55 initialization Comparing the while and for loops statement true condition evaluated false while loop statement true condition evaluated false for loop increment

56 unit 3 56 The for Statement H Like a while loop, the condition of a for statement is tested prior to executing the loop body H Therefore, the body of a for loop will execute zero or more times H It is well suited for executing a specific number of times that can be determined in advance

57 unit 3 57 The for Statement: examples for (int count=1; count < 75; count++) { System.out.println (count); } for (int num=5; num <= 10; num *= 2) { sum += num; System.out.println (sum); }

58 unit 3 58 The for Statement  Each expression in the header of a for loop is optional If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore makes an infinite loop If the increment is left out, no increment operation is performed H Regardless, both semi-colons are always required FlowIfElse

59 unit 3 59 The break and continue statements  The break statement, which we used with switch statements, can also be used inside a loop: when the break statement is executed, control jumps to the statement after the loop (the condition is not evaluated again)  A similar construct, the continue statement, can also be executed in a loop: when the continue statement is executed, control jumps to the end of the loop and the condition is evaluated

60 unit 3 60 Nested Loops - Multiplication Table int numRows = EasyInput.readInt(“Enter number of rows”); int numColumns = EasyInput.readInt(“Enter number of columns”); for (int row = 1; row <= numRows; row++) { for (int column = 1; column <= numColumns; column++) { System.out.print(row * column + “ “); } System.out.println(); }

61 unit 3 61 Nested Loops public class Mystery { public static void main(String[] args) { int dimension = EasyInput.readInt(“Enter dimension”); for (int j = 0; j < dimension; j++) { for (int k = 1; k < dimension - j; k++) { System.out.print(" "); } for (int k = 0; k < j; k++) { System.out.print("*"); } System.out.println(); } } }

62 unit 3 62 Why do We Need Indentation? public class Mystery { public static void main(String[] args) { InputRequestor in = new InputRequestor(); int dimension = EasyInput.readInt(“Enter dimension”); for (int j = 0; j < dimension; j++) { for (int k = 1; k < dimension - j; k++) { System.out.print(" "); } for (int k = 0; k < j; k++) { System.out.print("*"); } System.out.println(); }

63 unit 3 63 What you should be able to do now... write a program which can: H decide online which piece of code to follow H repeat a piece of code a number of times exercise: compute the divisors of a number (class Factor) in 3 different ways


Download ppt "Unit 3 1 Flow of control H We will talk about: conditional statements  if-then-else  logical and conditional operators  switch repetition statements."

Similar presentations


Ads by Google