Selection Statements (1)

Selection Statements (1)

SELECTION STATEMENTS (1) SELECTION STATEMENTS (1) if ifelse GC 201 Outline 1. Introduction 2. One-way selection: The if statement 2.1 With a single statement 2.2 With a block of statements 3. Two-way selection: The ifelse statement 3.1 With a single statement 3.2 With a block of statements 2 Selection 1. Introduction By default, the flow of a program is sequential. Selection statements alters the flow of execution depending on one or more specific conditions.

The condition(s) is/are specified by the programmer. In Java, the selection statements include: o The if statement With a single statement With a block of statements o The ifelse statement With a single statement With a block of statements o The nested if o The conditional operator ? o The switch statement 4 2. The if Statement With a single statement SYNTAX FLOWCHART True

if (logical expression) statement1; 1 Expression referred to as decision maker. Statement referred to as action statement. Logical Expression ? Statement 1 o False Execution continues at point 2 If the logical expression is false: o Statement 1 is NOT o executed Execution continues

at o 2 If the logical expression is true: Statement 1 is executed point 2 5 Write a program that read the grade of the student and if it is more than or equal 60; print Pass 6 Algorithm Start Read the grade G If G more than or equal to 60 Print Pass End Start Read G

False If G >= 60 True Print pass End Code 7 import java.util.*; public class grade { static Scanner console = new Scanner (System.in); public static void main(String[] args) { double grade; System.out.println("Enter Grade"); grade = console.nextDouble(); if (grade >= 60) System.out.println(PASS"; } } 3.1 The ifelse Statement With a single statement SYNTAX

if (logical expression) Statement1; else Statement2; If the logical expression is True otrue: Statement 1 is executed o Execution continues at point 2 Statement 1 If the logical expression is ofalse: Statement 2 is executed o Execution continues at point 2 1 Logical Expression ?

FLOWCHART False Statement 2 2 8 3.1 The ifelse Statement With a single statement PROGRAM 2: ANALYSIS Write a program that read two numbers and print the largest one INPUT Number1 : (variable: num1, type: int) Number2 : (variable: num2, type: int) OUTPUT Largest number PROCES S if (num1 > num2) print num1; if (num2 > num1) print num1; 9

3.1 The ifelse Statement With a single statement PROGRAM 3: Algorithm - Flowchart Start Read first number (num1) Read second number (num2) If num1 is larger than num2 Print num1 Start Read num1 Read num2 False else If num1 > num2 Print num2 True Print num2

Print num1 End 10 3.1 The ifelse Statement With a single statement - PROGRAM 3: CODE 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

// import necessary libraries import java.util.*; //contains the class Scanner public class ifElseStatement1 { // instantiate the object console from the class Scanner static Scanner console = new Scanner (System.in); public static void main (String[] args) { // Declaration section: to declare needed variables int num1, num2; // Input section: to enter values of used variables System.out.println (Enter number1); //prompt num1 = console.nextInteger(); System.out.println (Enter number2); //prompt num2 = console.nextInteger(); // Processing section: processing statements if (num1 > num2) System.out.println (num1); else System.out.println (num2); // Output section: display program output } // end main } // end class 11 Two-Way Selection 12 Example 4-14 //The following statement shows an example of a syntax error WHY ?

if (hours > 40.0); //Line 1 wages = 40.0 * rate + 1.5 * rate *(hours - 40.0); //Line 2 else //Line 3 wages = hours * rate; //Line 4 Because a semicolon follows the closing parenthesis of the if statement (Line 1), the else statement stands alone. The semicolon at the end of the if statement (see Line 1) ends the if statement. The statement at Line 2 separates the else clause from the if statement. That is, else is by itself. Because Java Programming: Problem Analysis to Program there is no From separate else statement in Java, this code generates a Design, D.S. Malik syntax error. 2.2 The if Statement With a block of statements SYNTAX

if (logical expression) { statement 1; statement 2; statement n; } FLOWCHART 1 True If the logical otrue: Statements o executed Execution point 2 If the logical ofalse: Execution point 2 expression is 1 & 2 are continues at

Statement 1 Statement 2 expression is continues at Logical Expression ? False 2 13 Write a program that read the grade of the student and if it is more than or equal 60; print Pass and the grade 14 Algorithm Start Read the grade G If G more than or equal to 60 Print Pass Print G End

Start Read G False If G >= 60 True Print pass Print G End Code import java.util.*; public class grade { // Class start 15 static Scanner console = new Scanner (System.in); public static void main(String[] args) { // method start double grade; System.out.println("Enter Grade"); grade = console.nextDouble(); if (grade >= 60) { // if block start System.out.println(PASS);

System.out.println(grade); } // if block end } // method end } // Class end 3.2 The ifelse Statement With a block of statements SYNTAX FLOWCHART if (logical expression) { Statement i; Statement i+1; Statement m; True } else { Statement i Statement j; Statement j+1; Statement i+1 Statement n; } 1 Logical Expression

? False Statement j Statement j+1 2 16 3.2 The ifelse Statement With a block of statements PROGRAM 4: ANALYSIS Write a program that assigns a special discount to an item according to its price, then calculates the net price as follows: If the price is greater than 1,000 SR then the customer is given a VIP status and the item is given a 15% discount; otherwise, the item is given an 18% discount. The program should also display the customer status if VIP. INPUT OUTPUT PROCES S Price of the item (variable: price, type: double) Discount (variable: discount, type: double) Net Price (variable: netPrice, type: double) Customer Status (variable: vip, type: boolean) if (price > 1000) 1) discount = 0.15 2) vip = true

if (price <= 1000) 1) discount = 0.18 2) vip = false netPrice = (1 discount) * price 17 3.2 The ifelse Statement With a block of statements - PROGRAM 4: CODE 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

25 26 27 28 29 30 // import necessary libraries import java.util.*; //contains the class Scanner public class ifElseStatementN { // instantiate the object console from the class Scanner static Scanner console = new Scanner (System.in); public static void main (String[] args) { // Declaration section: to declare needed variables double price, discount, netPrice; boolean vip; // Input section: to enter values of used variables System.out.println (Enter the price of the item); //prompt price = console.nextDouble(); // Processing section: processing statements if (price > 1000.0) // price is double { discount = 0.15; vip = true; } //end if(price > 1000.0) else { discount = 0.18;

vip = false; } //end else if(price > 1000) netPrice = (1 discount) * price; // Output section: display program output System.out.printf (Discount = %.2f, Net price = %.2f, vip = %5s, discount, netPrice, vip); } // end main } // end class 18 2. CONDITIONAL OPERATOR ? Also known as the ternary operator. SYNTAX Variable = (LogicalExpression1) ? Expression2: Expression3; If expression1 = true, then the result of the condition is expression2. Otherwise, the result of the condition is expression3. Example Output int x = 3, y = 5, min; min = (x <= y) ? x : y; max = (x >= y) ? x: y; System.out.println (min);

System.out.print (max); 1 3 2 5_ 19 2. CONDITIONAL OPERATOR ? Example int x = 3, y = 5, min; min = (x <= y) ? x : y; System.out.print (min); The above example is equivalent to the following code: 1 2 3 4 if (x <= y) min = x; else min = y; 20 Self-Check Exercises

Write a complete Java program that identifies the students whose grades are B. Write a complete Java program that reads two integer numbers num1 & num2, and performs a division if num2 is not equal to zero. Write a complete Java program that reads two integer numbers num1 & num2, and prints the smaller one. Write a complete Java program that identifies a negative number. Write a complete Java program that identifies an even number. W5.1 if + ifelse 21

Recently Viewed Presentations

  • Jonathan A. Havens - Medical University of South Carolina

    Jonathan A. Havens - Medical University of South Carolina

    Jonathan A. Havens. Jonathan Havens is the co-founder and co-chair of the Cannabis Law Practice at Saul Ewing Arnstein & Lehr LLP. He also serves as chair of the firm's Food and Beverage Practice and is a member of the...
  • Dystopias - scott.k12.ky.us

    Dystopias - scott.k12.ky.us

    18. A quest - to travel through unsafe settings, to deliver information or something valuable, to incite others to rebel, etc. 19. A coming-of-age theme - a young person matures quickly and learns his/her place in the order of things...
  • Chapter 1

    Chapter 1

    If there were unresolved difficulties in the first three stages (pregenital stages), Freud believed two difficulties could arise: Excessive frustration Overindulgence Heinz Kohut Proposed object-relations theory. A much less sexually based view of child development. An object is anything that...
  • Football

    Football

    Football Andrej Štellár History Association Football -England 19th century -Industrial revolution Modern Era -Born of "Soccer" The best of the best Pelé -greatest of all time Maradona -"Hand of God" Ronaldinho -young star Pele Diego Maradona Ronaldinho Football Clubs Real...
  • Cells of the Immune System - Longwood University

    Cells of the Immune System - Longwood University

    Lymphocytes "Naïve" (unprimed) B and T cells are indistinguishable Small, motile, non-phagocytic Ag binding induces entry to cell cycle G1 S G2 at which point, called lymphoblasts L'blasts soon differentiate into effector and memory cell populations B Lymphocytes Named from...
  • Irregular Verbs

    Irregular Verbs

    infinitive. past simple. past participle. meaning. arise. arose. arisen. levantarse, surgir. awake. awoke. awoken. despertarse. be. was / were. been. ser, estar. bear ...
  • Point-to-Point Topology - billatnapier.com

    Point-to-Point Topology - billatnapier.com

    Network Topologies Point-to-Point Topology Point-to-point (PTP) topology connects two nodes directly together. The following examples are pure point to point links: Two computers communicating via modems. A mainframe terminal communicating with a front end processor. A workstation communicating along a...
  • Middle School Social Studies - ASHLAND-GREENWOOD

    Middle School Social Studies - ASHLAND-GREENWOOD

    Middle School Social Studies Mr. Flynn ... F= Below 60 Remediation You may earn a passing grade on any assignment that you do not pass by correcting ALL incorrect answers, and retuning it to me within 5 school days. ......