Nested conditional statements. Previously discussed Conditional statements discussed so far: Syntax of the if-statement: if-statement if-else-statement.

Slides:



Advertisements
Similar presentations
Numeric literals and named constants. Numeric literals Numeric literal: Example: A numeric literal is a constant value that appears in a Java program.
Advertisements

Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Introduction to Computer Programming Decisions If/Else Booleans.
Nested conditional statements. A conditional statement (i.e., an if-statement or an if-else- statement) is also a statement We can use an if-statement.
The switch statement: an N-way selection statement.
Writing algorithms using the while-statement. Previously discussed Syntax of while-statement:
Writing algorithms using the for-statement. Programming example 1: find all divisors of a number We have seen a program using a while-statement to solve.
Programming a computer. What does programming a computer mean ? Programming a computer: Since a computer can only execute machine instructions (encoded.
The break and continue statements. Introduction There are 2 special statements that can affect the execution of loop statements (such as a while-statement)
Shorthand operators.
The character data type char
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
1 Introduction to Java Brief history of Java Sample Java Program Compiling & Executing Reading: => Section 1.1.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
The Rectangle Method. Introduction Definite integral (High School material): A definite integral a ∫ b f(x) dx is the integral of a function f(x) with.
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
Parameter passing mechanism: pass-by-value. Introduction In the last webpage, we discussed how to pass information to a method I have kept it (deliberately)
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
The dangling-else ambiguity. Previously discussed The Java compiler (translator) consider white space characters (i.e., SPACE, TAB and New line) as insignificant.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
What does a computer program look like: a general overview.
The scope of local variables. Murphy's Law The famous Murphy's Law says: Anything that can possibly go wrong, does. (Wikipedia page on Murphy's Law:
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Boolean expressions, part 2: Logical operators. Previously discussed Recall that there are 2 types of operators that return a boolean result (true or.
CSI 1390: Introduction to Computers TA: Tapu Kumar Ghose Office: STE 5014 Office hours: Thursday 1300 – 1400hrs.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
Working with arrays (we will use an array of double as example)
Introduction to programming in the Java programming language.
Assignment statements using the same variable in LHS and RHS.
Relational Operators Relational operators are used to compare two numeric values and create a boolean result. –The result is dependent upon the relationship.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
The if-else statement. The if-else statement in Java The if-else statement is the second conditional statement in Java The if-else statement selects one.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Chapter 5: Structured Programming
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
OOP (pre) Basic Programming. Writing to Screen print will display the string to the screen, the following print statement will be appended to the previous.
Mixing integer and floating point numbers in an arithmetic operation.
COMP Flow of Control: Branching 1 Yi Hong May 19, 2015.
Chapter 6. else-if & switch Copyright © 2012 Pearson Education, Inc.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
The Bisection Method. Introduction Bisection Method: Bisection Method = a numerical method in Mathematics to find a root of a given function.
Integer numerical data types. The integer data types (multiple !) The integer data types use the binary number system as encoding method There are a number.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
The while-statement. Syntax and meaning of the while-statement The LOOP-CONTINUATION-CONDITION is a Boolean expression (exactly the same as in the condition.
The assignment expressions. The assignment operator in an assignment statement We have seen the assignment statement: Effect: var = expr; Stores the value.
The while-statement. The loop statements in Java What is a loop-statement: A loop-statement is a statement that repeatedly executes statements contained.
Arithmetic expressions containing Mathematical functions.
Reading input from the console input. Java's console input The console is the terminal window that is running the Java program I.e., that's the terminal.
Introduction to array: why use arrays ?. Motivational example Problem: Write a program that reads in and stores away 5 double numbers After reading in.
SELF STUDY. IF STATEMENTS SELECTION STRUCTURE if selection statement if … else selection statement switch selection statement.
Working with floating point expressions. Arithmetic expressions Using the arithmetic operators: and brackets (... ), we can construct arithmetic expression.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
Simple algorithms on an array - compute sum and min.
The ++ and -- expressions. The ++ and -- operators You guessed it: The ++ and -- are operators that return a value.
1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING Switch Statement.
The if-else statement. Introducing the if-else statement Programming problem: Re-write the a,b,c-formula program to solve for complex number solutions.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Introduction to programming in java
Computer Programming Methodology Input and While Loop
SELECTION STATEMENTS (1)
Control Statement Examples
The Boolean (logical) data type boolean
Self study.
Lecture Notes – Week 2 Lecture-2
Lecture Notes - Week 2 Lecture-1. Lecture Notes - Week 2 Lecture-1.
The for-statement.
Presentation transcript:

Nested conditional statements

Previously discussed Conditional statements discussed so far: Syntax of the if-statement: if-statement if-else-statement if ( CONDITION ) ONE-statement

Previously discussed (cont.) Syntax of the if-else-statement: if ( CONDITION ) ONE-statement else ONE-statement

Nested conditional statements Fact: Therefore: A conditional statement (i.e., an if-statement or an if- else-statement) is also a statement We can use an if-statement or an if-else-statement in the then-part (and in the else-part) of a conditional statement !!!

Nested conditional statements (cont.) Nested conditional statement: Nested conditional statement = a conditional statement where the then-part and/or the else-part contains another conditional statement

Nested conditional statements (cont.) Note: You can nest conditional statement arbitrarily deep Obviously, deeper nesting makes the program difficult to understand You should: Use nested conditional statements only when necessary Try not to nest conditional statements too deeply

Programming example: determine the price for a hair cut Hair cut pricing of a saloon: Male customer: Boys (age ≤ 13): $10 Men (age > 13): $15 Female customer: Girls (age ≤ 13): $12 Women (age > 13): $25

Programming example: determine the price for a hair cut (cont.) Write a program that: Reads in the sex and the age Prints the price of the hair cut.

Programming example: determine the price for a hair cut (cont.) Algorithm:

Programming example: determine the price for a hair cut (cont.) Java program: public class NestedIf01 { public static void main(String[] args) { char sex; int age, price = 0; Scanner in = new Scanner(System.in); // Construct Scanner object sex = in.next().charAt(0); // Read in next char into sex age = in.nextInt(); // Read in next integer into age if ( sex == 'M' ) { // Then-part of outer if-else statement if ( age <= 13 ) { price = 10; // Case: boy <-- then-part of inner if-else }

Programming example: determine the price for a hair cut (cont.) else { price = 15; // Case: man <-- else-part of inner if-else } else { // Else-part of outer if-else statement if ( age <= 13 ) { price = 12; // Case: girl <-- then-part of inner if-else } else { price = 25; // Case: woman <-- else-part of inner if-else } System.out.println("Price = " + price); }

Programming example: determine the price for a hair cut (cont.) Explanation: Suppose the user enters: sex = 'M' and age = 11 Then the condition of the outer if-else-statement is satisfied and executes only the then-part of the outer if- else-statement: // Then-part of outer if-else statement if ( age <= 13 ) { price = 10; // Case: boy <-- then-part of inner if-else } else { price = 15; // Case: man <-- else-part of inner if-else }

Programming example: determine the price for a hair cut (cont.) Since the then-part of the outer if-else-statement is an if-else- statement, and the condition age <= 13 is satisfied, it will only execute the then-part: price = 10;

Programming example: determine the price for a hair cut (cont.) Graphically: path taken by program when input is sex = 'M' (male) and age = 11

Programming example: determine the price for a hair cut (cont.) Notice that only the statement(s) in then-part of the inner and outer if-else-statements are executed (because the conditions in the inner and outer if-else- statements are satisfied)

Programming example: determine the price for a hair cut (cont.) Another example: path taken by program when input is sex = 'F' (female) and age = 25

Programming example: determine the price for a hair cut (cont.) Note: The expression in.next() reads in a string from the keyboard The expression in.next().charAt(0) returns the first character in a string from read from the keyboard

Programming example: determine the price for a hair cut (cont.) Example Program: (Demo above code) –Prog file: NestedIf01.java How to run the program: Right click on link and save in a scratch directory To compile: javac NestedIf01.java To run: java NestedIf01

Programming example: assign a letter grade to a number grade Letter grade assignment: grade ≥ 90: A 80 ≤ grade < 90: B 70 ≤ grade < 80: C 60 ≤ grade < 70: D grade < 60: F

Programming example: assign a letter grade to a number grade (cont.) Write a program that: Reads in a number grade Prints the letter grade.

Programming example: assign a letter grade to a number grade (cont.) Algorithm using non-nested if-statements:

Programming example: assign a letter grade to a number grade (cont.) Java program: import java.util.Scanner; public class Grade01 { public static void main(String[] args) { double ng; String lg = ""; Scanner in = new Scanner(System.in); // Construct Scanner object

Programming example: assign a letter grade to a number grade (cont.) System.out.print("Enter numbger grade: "); ng = in.nextDouble(); // Read in next number into ng if ( ng >= 90 ) lg = "A"; if ( 80 <= ng && ng < 90 ) lg = "B"; if ( 70 <= ng && ng < 80 ) lg = "C"; if ( 60 <= ng && ng < 70 ) lg = "D"; if ( ng < 60 ) lg = "F"; System.out.println("Letter grade = " + lg); }

Programming example: assign a letter grade to a number grade (cont.) Example Program: (Demo above code) –Prog file: Grade01.java How to run the program: Right click on link and save in a scratch directory To compile: javac Grade01.java To run: java Grade01

Programming example: assign a letter grade to a number grade (cont.) Short-coming of the algorithm: It is inefficient Because the algorithm will always perform 5 individual tests (in the 5 different if-statements

Programming example: assign a letter grade to a number grade (cont.) Fact: The different cases are mutually disjoint E.g., when the first condition passes (i.e., grade ≥ 90), then the other 4 subsequent tests will all fail

Programming example: assign a letter grade to a number grade (cont.) The algorithm will still have to go through these "useless" tests to reach the print statement We can make use of the if-else-statement to shorten the execution

Improved algorithm to find numeric grade Improved algorithm to assign a letter grade:

Improved algorithm to find numeric grade (cont.) Explanation: The first if-else statement breaks the cases into: ng ≥ 90 and ng < 90:

Improved algorithm to find numeric grade (cont.) If ng ≥ 90, we can assign lg = "A"; Otherwise, the execution will enter the else-part

Improved algorithm to find numeric grade (cont.) The second if-else statement knows that ng = 80 to break the cases into: 80 ≤ ng < 90 and ng < 80:

Improved algorithm to find numeric grade (cont.) Because we know that ng < 90 when we are inside the else- part of the first if-else statement, when ng ≥ 80, we can assign lg = "B"; because 80 < ng ≤ 90 Otherwise, the execution will enter the else-part of the second if-else statement Inside the else-part of the second if-else statement, we know (for sure) that ng < 80. The rest of the algorithm follows the same reasoning process...

Improved algorithm to find numeric grade (cont.) Program in Java: (I omitted the import statement for brevity) public class Grade02 { public static void main(String[] args) { double ng; String lg = ""; Scanner in = new Scanner(System.in); // Construct Scanner object ng = in.nextDouble(); // Read in next number into ng

Improved algorithm to find numeric grade (cont.) if ( ng >= 90 ) lg = "A"; else { if ( ng >= 80 ) lg = "B"; else { if ( ng >= 70 ) lg = "C"; else { if ( ng >= 60 ) lg = "D"; else lg = "F"; } System.out.println("Letter grade = " + lg); }

Two-way selection A two-way selection is a choice between 2 mutually exclusive cases:

Two-way selection (cont.) The if-else-statement is known as a two-way selection statement because it can use to make a choice between 2 mutually exclusive cases:

A three-way selection construct A two-way selection is a choice between 3 mutually exclusive cases: The choices of A, B and C are mutually exclusive.

A three-way selection construct (cont.) A common way to ensure that the 3 choices are mutually exclusive is as follows:

A three-way selection construct (cont.) The 3-way selection construct can be implemented using the following nested if-else statements:

A three-way selection construct (cont.) Notes: Each of the conditions are mutually excusive The statement(s) S1; are executed only when condition1 = true The statement(s) S2; are executed only when (condition1 = false and condition2 = true) The statement(s) S3; are executed only when (condition1 = false and condition2 = false)

A three-way selection construct (cont.) The 3-way selection written in Java: if ( conditionX ) { statements executed only when: conditionX = true } else { if ( conditionY ) --+ { | statements executed only when: | conditionX = false | and conditionY = true | } | One statement!! else | { | statements executed only when: | conditionX = false | and conditionY = false | } --+ }

A three-way selection construct (cont.) Since there is one statement in the else-part, we do not need to use a block

A three-way selection construct (cont.) The popular way to write a 3-way selection in Java: if ( conditionX ) { statements executed only when: conditionX = true } else if ( conditionY ) --+ { | statements executed only when: | conditionX = false | and conditionY = true | } | One statement!! else | { | statements executed only when: | conditionX = false | and conditionY = false | } --+

The N-way selection construct The 3-way selection construct can be generalized into an N-way selection

The N-way selection construct (cont.) A N-way selection construct looks like the following: if ( condition 1 ) { S 1 ; (one or more statements) } else if ( condition 2 ) { S 2 ; (one or more statements) } else if ( condition 3 ) { S 3 ; (one or more statements) }... else if ( condition N-1 ) { S N-1 ; (one or more statements) } else { S N ; (one or more statements) }

The N-way selection construct (cont.) Notes: S 1 will be executed (only) when condition 1 = true S 2 will be executed (only) when (condition 1 = false and condition 2 = true) S 3 will be executed (only) when (condition 1 = false, condition 2 = false and condition 3 = true) And so on...

The N-way selection construct (cont.) Example: the number grade program can be written using an N-way selection public class Grade03 { public static void main(String[] args) { double ng; String lg = ""; Scanner in = new Scanner(System.in); // Construct Scanner object ng = in.nextDouble(); // Read in next number into ng

The N-way selection construct (cont.) if ( ng >= 90 ) { lg = "A"; } else if ( ng >= 80 ) { lg = "B"; } else if ( ng >= 70 ) { lg = "C"; } else if ( ng >= 60 ) { lg = "D"; } else { lg = "F"; } System.out.println("Letter grade = " + lg); }

The N-way selection construct (cont.) Example Program: (Demo above code) –Prog file: Grade03.java How to run the program: Right click on link and save in a scratch directory To compile: javac Grade03.java To run: java Grade03