Presentation is loading. Please wait.

Presentation is loading. Please wait.

Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.

Similar presentations


Presentation on theme: "Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision."— Presentation transcript:

1 Control Structures- Decisions

2 Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision making in programming Basically computer decisions are made to answer “Yes” and “No” type of questions The “Yes” and “No” type of questions are usually presented in a “true” or “false”, or “on” or “off” decision format The true and false values are based on Boolean algebra and will always result in Boolean values

3 Sequence Structure Program statements are typically arranged in a logical structure Logical arrangement is also known as sequence structure In sequence structure, the statements are arranged to perform one task after another In this way, programming statements can perform the same task in the same order each time they are executed The sequence structure can be altered based on decisions or some conditions The conditions are based on control structures

4 What are Control Structures? Java will execute your code in a specific sequence Control structures provide different ways to alter the natural sequence of execution in a Java program In other words, they act as “direction signals” to control the path a program takes Control structures include: block statements (Sequence) decision statements (Selection) Loops (Iteration or Repetition)

5 Making Decisions with Computers

6 Deciding with the if statement In Java, the if statement is the simplest statement for making all kinds of decisions The simplest structure for the if statement syntax is shown below if( booleanExpression ) statement for true expression; next statement; The expression in the parentheses is a Boolean expression that produces Boolean true or false Note that there is no semicolon at the end of the parentheses that follows the if statement That statement ends at the end of statement true

7 If Statements (Single alternative) The “if” decision statement executes a statement conditionally if (booleanExpression) { statement true; } next statement; The expression must produce a boolean value, either true or false If expression returns true, statement true is executed and then next statement If expression returns false, statement true is not executed and the program continues at next statement Whether the expression evaluates as true or false, the next statement will be executed

8 execute true statement execute next_statement expression is true ? if (booleanExpression) true statement next_statement yes no

9 Common errors with the if Consider an integer variable age with value 14 We want to print a message when the value of age is actually 14 if( age == 14 ); // the semicolon will terminate the if test statement System.out.println( “This is a teenager ” ); System.out.println( “This is not a teenager ” ); The semicolon following the if condition will terminate the if condition All the println() statements will be executed

10 If Statement Errors Another source of error is the use of the assignment operator (=) instead of using the double equal (==) for comparison (Boolean test) The expression age = 14 does not compare age to 14 The expression age = 14 attempts to assign the value 14 to age ( requires a Boolean test) Therefore the use of the assignment operator in an if statement is illegal In Java, it is illegal to interchange the positions of the variable and the constant as in 14 == age

11 If-else Statements (dual-alternative) The basic form of the “if” statement can be extended by adding the “else” clause if (booleanExpression) { statement1; } else{ statement2; } next statement; The if-else is used when one or the other of two possible actions or tasks is to be performed Again, the expression must produce a boolean true or false If the expression returns true, statement1 is executed and then next statement is executed. If the expression returns false, statement2 is executed and then next statement is executed.

12 The dual if.. else The if..else statement provides the mechanism for to perform one action –When a Boolean expression results in true and –To perform a different action when the Boolean expression results in a false if( gender == ‘M’) System.out.println( “I am male” ) else System.out.println( “I am female” ) In the above example, when the value of gender is actually the character M the message “I am male” is executed the reverse is true

13 expression is true ? execute statement1 execute statement2 execute next_statement if (booleanExpression){ statement1 } else { statement2 } next_statement noyes

14 Here is an example of chained if-else statements: if (grade == 'A') System.out.println("You got an A."); else if (grade == 'B') System.out.println("You got a B."); else if (grade == 'C') System.out.println("You got a C."); else System.out.println("You got an F.");

15 The if test and Multiple Statements Sometimes it becomes necessary to perform more than one task in an if statement To perform more than one task that depends on the outcome of a Boolean test The number of tasks can be grouped by a pair of curly brackets The use of the curly brackets is required if the multiple statements are to be treated as a block Without the use of the curly brackets, all the statements apart from the one immediately after the Boolean test would be executed whether the Boolean test results in a true or false

16 The else with Multiple Statements Sometimes it becomes necessary to perform more than one task in an else statement To perform more than one task that depends on the outcome of a Boolean else test The number of tasks can be grouped by a pair of curly brackets just as in the case of the if test The use of the curly brackets is required if the multiple statements are to be treated as a block Without the use of the curly brackets, all the statements apart from the one immediately after the Boolean test would be executed whether the Boolean test results in a true or false

17 Nested if and else if Conditions Sometimes an if or an else statement may be required within another if or else statement An if statement may contain another if or an else statement The inner if or else statement is said to be nested within the outer if condition The nested condition can also contain another nested condition Nested conditions can be used to implement multiple alternatives Nested conditions are mainly used when two or more conditions must be fulfilled before some task is performed

18 Sample Nested Condition The code below is a nested code if statement if( birthDate >= 1957 ) { if( birthCountry == “Ghana” ) // a nested if condition System.out.println( “Purely Ghanaian born” ); } else { System.out.println( “Either born in the Gold Coast or born outside Ghana” ); }

19 The Logical AND and the OR operators The nested if conditions can be replaced by the use of the logical AND ( && ) operator This is achieved by placing the operator between two Boolean expressions if( org == “NGO” && annualRevenue > 100 ) System.out.println( “Revenue taxable” ); else System.out.println( “Revenue is tax free” ); Note that the two conditions surrounding the logical AND operator must both evaluate to true for the revenue to be taxable

20 Using the Logical OR (||) operator The nested if conditions can also be replaced by the use of the logical OR ( || ) operator This is achieved by placing the operator between two Boolean expressions if( totalSales >= 1500 || itemSold >= 3 ) System.out.println( “Earns 5% commission” ); else System.out.println(“No commission earned”); Note that at least one of the two conditions surrounding the logical OR operator must evaluate to true to earn the commission

21 Switch Statements The if statement makes a selection based on a single true or false condition The use of several if statements can result in codes that are difficult to read The switch statement enables you to test several cases generated by a given expression. The expression must produce a result of type char, byte, short or int and must be enclosed in a parentheses It does not test for data of type long, float, or double. The switch statement is useful for testing a single variable against a series of integer or character values

22 Structure of the switch Statement The structure of the switch statement has four keywords –The switch keyword starts the structure and is immediately followed by an expression in parentheses –The case keyword which is followed by one of the possible test result values from the expression and is terminated by a colon –The break keyword which is optionally used to terminate the switch structure at the end of each case and is terminated by a semicolon –The default keyword which is also used as an option to perform any other action if the switch expression does not match any of the case values also terminated by a colon

23 Syntax of the Switch switch(expression) { case value1: statement1; case value2: statement2; default: default statement; } In the above example every statement after the true case value will be executed because the break keyword has been omitted

24 y y n n switch (expression){ case value1: // Do value1 thing case value2: // Do value2 thing... default: // Do default action } // Continue the program expression equals value1 ? Do value1 thing Do value2 thing Do default action expression equals value2 ? Continue the program

25 Break Statements in Switch Statements The break; statement tells the computer to exit the switch structure For example: switch(expression) { case value1: statement1; break; case value2: statement2; break; default: default statement; break; }

26 expression equals value1 ? expression equals value2 ? Do default action Do value1 thing Do value2 thing break Continue the program switch (expression){ case value1: // Do value1 thing break; case value2: // Do value2 thing break;... default: // Do default action break; } // Continue the program y y n n

27 Another switch Example int stage = 2; // must be initialised to avoid error switch( stage ) { case 1: System.out.println( "This is Stage 1." ); break; case 2: System.out.println( "This is Stage 2"); break; case 3: System.out.println( "This is Stage 3." ); break; default: System.out.println( "Sorry no such exists! "); }

28 Explaining the Sample Switch code The switch begins by evaluating the stage variable in the switch statement If the stage value matches case 1, the string “ This is Stage 1 ” is executed. The break statement causes the entire switch to terminate and execution continues outside the switch structure If the stage variable does not match the first case value, the next case value is compared. If non of the cases matches the switch statement variable, the default statement will be executed Without the break statements all cases would be executed

29 Remember the Example… Here is an example of chained if-else statements: if (grade == 'A') System.out.println("You got an A."); else if (grade == 'B') System.out.println("You got a B."); else if (grade == 'C') System.out.println("You got a C."); else System.out.println("You got an F.");

30 Another way to do this same example is to use the switch statement Complicated if-else chains can be rewritten with the switch statement switch (grade) { case 'A': System.out.println("You got an A."); break; case 'B': System.out.println("You got a B."); break; case 'C': System.out.println("You got a C."); break; default: System.out.println("You got an F."); }

31 Using the Conditional AND (?) operator In addition to the if statement and the switch case structure Java provides the conditional AND (?) for decision making The conditional AND operator requires three expressions separated by a question mark and a colon The conditional operator is used as an abbreviated form of the if…else structure The syntax of the conditional operator is of the form testExpression ? trueValue : falseValue ;

32 The conditional AND operator Using the expression testExpression ? trueResult : falseResult; The first expression, testExpression is a Boolean expression that evaluates to true or false When testExpression is true, the entire expression takes the trueResult value When testExpression is false, the entire expression takes the falseResult value Consider the condition when x = 4 and y = 7, the expression smallerValue = ( x < y) ? x : y ; will assign false to the variable smallerValue;

33 Using the NOT (!) operator The NOT operator is the exclamation sign It is used to negate any Boolean expression Any expression that evaluates to true becomes false when preceded by the NOT operator Any false expression preceded by the NOT operator becomes true As an example, and let us consider a situation when a hundred year old person is considered a centenarian In that case when it is negated it is no longer a centenarian

34 Using the NOT operator if( age >= 100) System.out.println( “A centenarian is found” ); else System.out.println( “No centenarian is found” ); if( ! ( age >= 100) )// the negated statement System.out.println( “No centenarian is found” ); else System.out.println( “A centenarian is found” );

35 SHOT TEST 1.In the switch statement expression must produce a result of what type? 2.What must be used to separate each section of a for statement. 3.Which statement causes a program to go back to the statement that began a loop and then keep going from there. 4.Write a for loop that outputs 100  1 in reverse sequence. 5.Write a for loop that outputs all numbers that are divisible by 3 between 0-50. char, byte, short, int

36 SHORT EXERCISE 1.In the switch statement expression must produce a result of what type? 2.What must be used to separate each section of a for statement. 3.Which statement causes a program to go back to the statement that began a loop and then keep going from there. 4.Write a for loop that outputs 100  1 in reverse sequence. 5.Write a for loop that outputs all numbers that are divisible by 3 between 0-50. char, byte, short, int ; (semi-colon)

37 SHORT EXERCISE In the switch statement expression must produce a result of what type? What must be used to separate each section of a for statement. Which statement causes a program to go back to the statement that began a loop and then keep going from there. Write a for loop that outputs 100  1 in reverse sequence. Write a for loop that outputs all numbers that are divisible by 3 between 0-50. char, byte, short, int ; (semi-colon) continue

38 SHORT EXERCISE In the switch statement expression must produce a result of what type? What must be used to separate each section of a for statement. Which statement causes a program to go back to the statement that began a loop and then keep going from there. Write a for loop that outputs 100  1 in reverse sequence. Write a for loop that outputs all numbers that are divisible by 3 between 0-50. char, byte, short, int for(int i=100; i>=0;i--) { System.out.println(i);} ; (semi-colon) continue

39 SHORT EXERCISE In the switch statement expression must produce a result of what type? What must be used to separate each section of a for statement. Which statement causes a program to go back to the statement that began a loop and then keep going from there. Write a for loop that outputs 100  1 in reverse sequence. Write a for loop that outputs all numbers that are divisible by 3 between 0-50. char, byte, short, int for(int i=100; i>=0;i--) { System.out.println(i);} ; (semi-colon) continue for(int i=0;i<=50;i++) { if(i%3 == 0) { SOP(i); } }


Download ppt "Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision."

Similar presentations


Ads by Google