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

Slides:



Advertisements
Similar presentations
Control Structures.
Advertisements

1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Control Structures Corresponds with Chapters 3 and 4.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Introduction to Java Programming, 4E Y. Daniel Liang.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
C++ for Engineers and Scientists Third Edition
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
The switch Statement, DecimalFormat, and Introduction to Looping
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Visual C# 2005 Decision Structures. Visual C# Objectives Understand decision making Learn how to make decisions using the if statement Learn how.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Jaeki Song ISQS6337 JAVA Lecture 04 Control Structure - Selection, and Repetition -
Chapter 4: Making Decisions. Understanding Logic-Planning Tools and Decision Making Pseudocode – A tool that helps programmers plan a program’s logic.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
CPS120: Introduction to Computer Science Decision Making in Programs.
Lecture 4 Control Structures MIT – AITI What are Control Structures? Control structures are a way to alter the natural sequence of execution in.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Chapter 05 (Part III) Control Statements: Part II.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
Control statements Mostafa Abdallah
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Lecture 4b Repeating With Loops
Java Programming Fifth Edition
Chapter 3 Control Statements
REPETITION CONTROL STRUCTURE
COMP 14 Introduction to Programming
Selection (also known as Branching) Jumail Bin Taliba by
Selections Java.
The switch Statement, and Introduction to Looping
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Chapter 4: Making Decisions.
Control Structures.
Lecture 3- Decision Structures
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 3 Loops Section 3.3 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Topics The if Statement The if-else Statement Comparing Strings
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 4: Making Decisions.
JavaScript: Control Statements.
Topics The if Statement The if-else Statement Comparing Strings
Outline Altering flow of control Boolean expressions
Chapter 3:Decision Structures
Chapter 7 Conditional Statements
Chapter 6 Control Statements: Part 2
Lab5 PROGRAMMING 1 Loop chapter4.
Chapter 4: Control Structures I (Selection)
The System.exit() Method
Control Structure Chapter 3.
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
PROGRAM FLOWCHART Selection Statements.
Using C++ Arithmetic Operators and Control Structures
Selection Control Structure
Controlling Program Flow
Presentation transcript:

Control Structures- Decisions

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

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

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)

Making Decisions with Computers

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

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

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

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

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

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.

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

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

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.");

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

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

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

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” ); }

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

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

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

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

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

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

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; }

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

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! "); }

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

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.");

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."); }

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 ;

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;

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

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” );

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 char, byte, short, int

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 char, byte, short, int ; (semi-colon)

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 char, byte, short, int ; (semi-colon) continue

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 char, byte, short, int for(int i=100; i>=0;i--) { System.out.println(i);} ; (semi-colon) continue

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 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); } }