Java Programming: From The ground Up  Chapter 4 Selection and Decision: if Statements.

Slides:



Advertisements
Similar presentations
Flow of Control Chapter 3.
Advertisements

The if-else Statements
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 10, 2009.
Control Structures Corresponds with Chapters 3 and 4.
Topic 03 Control Statements Programming II/A CMC2522 / CIM2561 Bavy Li.
Week 4 Selections This week shows how to use selection statements for more flexible programs. It also describes the various integral types that are available.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
true (any other value but zero) false (zero) expression Statement 2
Introduction to Java Programming, 4E Y. Daniel Liang.
1 Conditionals In many cases we want our program to make a decision about whether a piece of code should be executed or not, based on the truth of a condition.
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Tutorial 4 Decision Making with Control Structures and Statements Section A - Decision Making JavaScript Tutorial 4 -Decision Making with Control.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
COMP 110 Introduction to Programming Mr. Joshua Stough September 19, 2007.
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control if-else and switch statements.
UNIT II Decision Making And Branching Decision Making And Looping
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Java Programming: From the Ground Up
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
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.
Chapter 4 Introduction to Control Statements Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else Statements Section 4.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Conditional Statement Chapter 8. Conditional Statements Are statements that check an expression then may or may not execute a statement or group of statement.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
PROGRAM FLOW CHAPTER3 PART1. Objectives By the end of this section you should be able to: Differentiate between sequence, selection, and repetition structure.
Copyright 2003 Scott/Jones Publishing Making Decisions.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Chapter 6. else-if & switch Copyright © 2012 Pearson Education, Inc.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Java Programming Fifth Edition Chapter 5 Making Decisions.
IT CS 200: C ONDITION Lect. Napat Amphaiphan. T HE ABILITY TO CONTROL THE FLOW OF YOUR PROGRAM, LETTING IT MAKE DECISIONS ON WHAT CODE TO EXECUTE 2.
Control statements Mostafa Abdallah
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
Decision Statements, Short- Circuit Evaluation, Errors.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
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
Chapter 5 – Decision Making. Structured Programming Sequence Selection Repetition yesno yes no.
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 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
A First Book of C++ Chapter 4 Selection.
Branching statements.
Selection (also known as Branching) Jumail Bin Taliba by
Java Programming: From The ground Up
Lecture 3- Decision Structures
EGR 2261 Unit 4 Control Structures I: Selection
Flow of Control.
Chapter 3 Branching Statements
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Control Structures: Selection Statement
PROGRAM FLOWCHART Selection Statements.
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Control Structures: Selection Statement
Branching statements Kingdom of Saudi Arabia
Selection Statements August 22, 2019 ICS102: The course.
Presentation transcript:

Java Programming: From The ground Up  Chapter 4 Selection and Decision: if Statements

The if Statement Example: if (sale < 25.00) { total += SHIPPING_FEE; System.out.println("Shipping is $5.00"); } Execution of this statement proceeds as follows: 1. The boolean expression sale < is evaluated. 2. If the boolean expression is true, the two statements enclosed by the curly braces are executed. 3. If the boolean expression is false, the statements enclosed by the braces are skipped.

The if Statement The syntax for an if statement is: if ( boolean-expression) { statement-1; statement-2; … statement-n; }

The if Statement Terminology: An if statement is also termed a conditional or selection statement. The phrase if (boolean-expression) is called the if clause. The boolean expression is also called a boolean condition (or simply a condition). The statement-list enclosed by curly braces is a block or compound statement.

The if Statement A block is a group of statements enclosed by matching curly braces. If the statement-list consists of a single statement the braces may be omitted. A single statement without the braces is not considered a block.

The if Statement An if statement that does not contain curly braces: 1. int max = a; //a is biggest so far 2. if (b > max) // is b bigger than the current maximum 3. max = b; // if so, set max to b 4. if (c > max) // is c bigger than the current maximum? 5. max = c; // if so set max to c 6. System.out.println (“The maximum value is ” +max); Alternatively, the same fragment can be written using curly braces: int max = a; if (b > max) { max = b; } if (c > max) { max = c; } System.out.println(“The maximum value is “+max);

The if-else Statement The if-else statement provides an alternative: if the boolean condition is true one group of statements executes, but if the condition evaluates to false a different group is selected. 1. System.out.print(" 1 to convert from dollars to euros2 from euros to dollars: " ); 2. transactionType = input.nextInt(); 3. if (transactionType == 1) // dollars to euros 4. { 5. System.out.print("Number of dollars: "); 6. dollars = input.nextDouble(); 7. euros = dollars/DOLLARS_PER_EURO; 8. System.out.println("Number of euros: " + euros); 9. } 10. else // otherwise euros to dollars 11. { 12. System.out.print("Number of euros: "); 13. euros = input.nextDouble(); 14. dollars = euros* DOLLARS_PER_EURO; 15. System.out.println("Number of dollars: " + dollars); 16. }

The if-else Statement Lines 12 through 25 constitute a single if-else statement. Line 3 (transactionType == 1) is a boolean condition. If this condition is true then the statements on lines 4 through 9 are selected and those on line10 through16 are skipped. If the boolean condition is false, then the block consisting of lines 4 through 9is ignored and the block of statements on lines 10 through 16 executes.

The if-else Statement The syntax of the if else statement is: if (boolean-expression) statement-list-1 else statement-list-2 where statement-list-1 and/or statement-list-2 signify single statements or a block. If boolean-expression is true then: statement-list-1 is executed and statement-list-2 is skipped; otherwise, statement-list-1 is skipped and statement-list-2 is executed. Every time an if-else statement is encountered, one of the two statement-lists always executes.

Nested if-else Statements An if-else statement can be nested inside another if-else statement:

Nested if-else Statements 1. int grade = input.nextInt(); //user supplies a grade 2. if ( grade >=70 ) 3.{ 4. if ( grade >= 90) 5. System.out.println( “High pass”); 6. else 7. System.out.println(“Pass”); 8. } 9.else 10. System.out.println(“Fail”); If the value of grade is 65, the condition on line 2 is false and the corresponding else clause of line 10 executes. The output is “Fail.” The if-else statement on lines 4-7 is skipped. If grade is 75, the boolean condition on line 2 is true. As a result, the if-else statement on lines 4 -7 executes and the else clause on line 9 is skipped. Because grade is not greater than or equal to 90, the boolean condition of line 4 is false and the else clause of line 7 executes. The output is “Pass.” If grade has the value 95, the condition of line 2 is true so the if-else statement of lines 4-7 executes and the else clause on line 9 is skipped. This time grade is greater than or equal to 90, so the condition on line 4 is true and the println(...) statement on line 5 executes. The output is “High pass.”

An Ambiguity: The “Dangling else” Problem The code segment: if (a > 1) if (b > 10) System.out.println(“D’oh!”); // says Homer Simpson else System.out.println(“ What’s up, Doc?”); // says Bugs Bunny contains two if clauses, one else clause, and illustrates a classic ambiguity. Which if clause, (a > 1), or (b > 10), is associated with the single else clause? Two possible interpretations.

An Ambiguity: The “Dangling else” Problem Interpretation 1: if (a > 1) { if (b > 10) System.out.println( “D’oh!”); // Homer Simpson else System.out.println(“ What’s up, Doc?”); // Bugs Bunny } The single else clause is paired with the second if clause.

An Ambiguity: The “Dangling else” Problem Interpretation 2: if (a > 1) { if (b > 10) System.out.println( “D’oh!”); //Homer Simpson } else System.out.println(“ What’s up, Doc?”); //Bugs Bunny The else clause belongs to the first if clause.

An Ambiguity: The “Dangling else” Problem To emphasize the difference between the two if-else pairings, consider the following four cases: 1. a = 3; b = 20; 2. a = 3; b = 5; 3. a = 0; b = 20; 4. a = 0; b = 5; With each of the above assignments (1-4), interpretation 1 produces the following output: 1. D’oh! 2. What’s up, Doc? 3. //No output is displayed 4. //No output is displayed

An Ambiguity: The “Dangling else” Problem Using the second interpretation, the results are different: 1. D’oh! 2. //No output is displayed 3. What’s up, Doc? 4. What’s up, Doc? How does Java pair an if with an else? An else is paired with the innemost if. Thus, interpretation 1 is correct.

The else-if Construction if (boolean-expression1) statement-list-1; else if (boolean-expression2) statement-list-2; else if (boolean-expressionlist-3) statement-list-3; … else statement-list-n; The if clauses are examined sequentially, one after the next. The first time a boolean condition has the value true, the statement (block) attached to that if clause executes and all subsequent code of the nested if-else statement is skipped. If none evaluates to true, the statement attached to the final else clause executes.

The else-if Construction if (score >= 90) System.out.println("Score: "+score+". Your grade is an A"); else if (score >= 80) System.out.println("Score: "+score+". Your grade is a B"); else if (score >=70) System.out.println("Score: "+score+". Your grade is a C"); else if (score >=60) System.out.println("Score: "+score+". Your grade is a D"); else System.out.println("Score: "+score+". Your grade is an F");

The switch Statement Java’s switch statement sometimes offers a more compact alternative to the else-if construction. The following else-if segment displays a one-word description for each letter grade ‘A’ through ‘F’: if ( grade == ‘A’) System.out.println(“Excellent”); else if (grade ==’B’) System.out.println(“ Good”); else if (grade ==’C’) System.out.println(“Average”); else if (grade ==’D’) System.out.println(“Passing”); else System.out.println(“Failure”);

The switch Statement The following switch statement accomplishes the same task: switch(grade) { case ‘A’: System.out.println(“Excellent”); break; case ‘B’: System.out.println(“Good”); break; case ‘C’: System.out.println(“Average”); break; case ‘D’: System.out.println(“Passing”); break; default : System.out.println(Failure”); } The value of grade is compared to each “case value” (‘A,’ ‘B,’ ‘C,’ and ‘D’) until a match is found. If one of the case values matches the value of grade, the corresponding println(...) statement executes and the break statement terminates the switch statement. If no case value matches the value of grade then the statement of the default case executes.

The switch Statement The switch statement behaves in a manner similar to the else-if construction In its simplest form, the syntax of the switch statement is: switch (switch-expression) { case casevalue-1: statement; statement; … statement; break; case casevalue-2: statement; statement; … statement; break; … case casevalue-n: statement; statement; … statement; break; default: statement; … statement; }

The switch Statement The switch statement works as follows: switch-expression is evaluated. The list of case values (casevalue-1, casevalue-2, …, casevalue-n) is searched in order until one of the case values matches the value of switch-expression. If a match is found, the statements associated with that case execute, and the break statement causes the termination of the switch statement. If no match is found, the statements of the default case execute. The default case is optional. If you omit the default case and none of the case values match switch-expression, then the switch statement performs no action. The break statements are also optional.

The switch Statement The value of switch-expression must be an integer or character type; switch-expression cannot evaluate to a floating point or boolean type. The case values must be constants.

The switch Statement Any integer or character expression is permissible: // test1, test 2, and test3 are each integers with values // in the range 0-4. switch( (test1+test2+test3)/3) // integer division { case 4: System.out.println(“Grade: A”); break; case 3: System.out.println(“Grade: B”); break; case 2: System.out.println(“Grade: C”); break; case 1: System.out.println(“Grade: D”); break; default: System.out.println(“Grade: F); }

The switch Statement There are circumstances when you might want to omit some break statements from a switch statement. Roll dice. In craps, If the value shown on a pair of dice is 7 or 11 the player wins. if the value is 2, 3, or 12, the player loses. Any other value is called the player’s “point” and the game is not (yet) resolved.

Craps switch(diceValue) { // 7 or 11 is a win case 7: case 11: System.out.println(“You rolled “ + value + “ you win!); break; //2,3, or 12 is a loss case 2: case 3: case 12: System.out.println(“You rolled “+ value + “ you lose!”); break; // 4, 5, 6, 8, 9, or 10 is the “point” default: System.out.println(“ Your point is“ + value); }

The switch Statement An equivalent else-if construction is: if (diceValue == 7 || diceValue == 11) System.out.println(“You rolled “ + value + “ you win!); else if (diceValue == 2 || diceValue == 3 || diceValue == 12) System.out.println(“You rolled “+ value + “ you lose!”); else System.out.println(“You rolled “ + value + “that’s you point!”);