Conditional Statements

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
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.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
The switch Statement, DecimalFormat, and Introduction to Looping
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
CPS120: Introduction to Computer Science Decision Making in Programs.
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.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
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.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
1 Week 6 Branching. 2 What is “Flow of Control”? l Flow of Control is the execution order of instructions in a program l All programs can be written with.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Copyright 2003 Scott/Jones Publishing Making Decisions.
Chapter 4 Control Structures I. Chapter Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate.
Logical Operators, Boolean Variables, Random Numbers This template was just too good to let go in one day!
CPS120: Introduction to Computer Science Decision Making in Programs.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
CPS120: Introduction to Computer Science Decision Making in Programs.
Dr. Sajib Datta Jan 23,  A precedence for each operator ◦ Multiplication and division have a higher precedence than addition and subtraction.
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Dr. Sajib Datta Sep 3,  A new operator used in C is modulus operator: %  % only used for integers, not floating-point  Gives the integer.
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
If/Else Statements.
Chapter 3 Selection Statements
Java Programming Fifth Edition
INTERMEDIATE PROGRAMMING USING JAVA
COMP 14 Introduction to Programming
Introduction to Python
Selection (also known as Branching) Jumail Bin Taliba by
Selections Java.
The switch Statement, and Introduction to Looping
Chapter 4: Making Decisions.
CHAPTER 4 Selection CSEG1003 Introduction to Computing
Lecture 3- Decision Structures
EGR 2261 Unit 4 Control Structures I: Selection
Operator Precedence Operators Precedence Parentheses () unary
Boolean Expressions and If
User input We’ve seen how to use the standard output buffer
JavaScript: Control Statements.
Control Structures – Selection
Conditionals & Boolean Expressions
Selection (if-then-else)
Selection CSCE 121 J. Michael Moore.
Chapter 3:Decision Structures
Java Programming Control Structures Part 1
Chapter 7 Conditional Statements
Module 4 Loops.
Topics 4.1 Relational Operators 4.2 The if Statement
Chapter 4: Control Structures I (Selection)
Logic of an if statement
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Chapter 3: Selection Structures: Making Decisions
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
CprE 185: Intro to Problem Solving (using C)
Just Enough Java 17-May-19.
Welcome back! October 11, 2018.
Selection Control Structure
Controlling Program Flow
Presentation transcript:

Conditional Statements Module 3 Conditional Statements

Conditional Statements allow you to do different things in different situations. Imagine driving a car. You see a stoplight ahead. What you do next is dependent on the state of the stoplight. IF the stoplight is green, THEN you continue. IF the stoplight is yellow, THEN you prepare to stop. IF the stoplight is red, THEN you stop.

Or what about age and voting? What do we want to do? 1) Ask the user for their age. 2) IF they are at least 18 years old, THEN tell them that they can vote. 3) ELSE inform them that they are too young to vote We can use an if/else statement to do this in Java!

Conditional Statement If the conditional statement is false, everything after the else is executed. If the conditional statement is true, everything within the first set of curly braces is executed. If/else statement Scanner kb = new Scanner(System.in); System.out.print(“How old are you? “); int age = kb.nextInt(); if(age >= 18) { System.out.println(“You can vote!”); } else System.out.println(“Sorry, can’t vote yet.”); Conditional Statement

Conditional Statements are statements that evaluate to true or false. Conditional statements often use an equality operator: Operator Meaning == Equal (only for primitive data) != Not equal > Greater than >= Greater than or equal to < Less than <= Less than or equal to

Now your turn… Ask the user for two numbers. If the numbers are the same, output “Same” Otherwise output “Different”

Now your turn…

Let’s do another one Ask the user for a String. If the String starts with the letter ‘a’, output “A is for Apple!” Otherwise, output “Nevermind.”

Notice that this is giving us a char, not a String. Let’s do another one Notice that this is giving us a char, not a String.

Classes are different if(x == 5) if(s.equals(“hello”)) If you want to check if two numbers are equal, or two chars are equal, use == If you want to check if two Strings (or any other type of classes) are equal, use .equals if(x == 5) if(s.equals(“hello”)) You MUST use .equals for ALL class types! This is extra tricky because if(s == “hello”) will compile just fine. It just won’t work properly!

What if our situation is a bit more complicated? Ask the user for their age. Describe them as a child, teenager, or adult depending on their answer. Give it a try! Hint – you can nest if/else statements

What if our situation is a bit more complicated? Notice we break the possible options into two. Then we do it again. If statements always break the world into two parts.

When you find yourself nesting if/else statements, there’s a better way We can use an “else if” to restructure our code: Notice the final else has no parentheses after it. We can have as many options as we want using “else if”

What would be the output of the following code? AB BC AC ABC Socrative

What would be the output of the following code? If/else statements do not “fall through”. We stop at the first section whose condition is met. A B C AB BC AC ABC Socrative

Use .equalsIgnoreCase to ignore the case of the order Your turn… Use .equalsIgnoreCase to ignore the case of the order You’ve been hired by Starbucks to put together a new automated computer system. Ask the user if they would like an ice tea, latte, or cappuccino If they chose ice tea, tell them they owe $3.50 If they chose latte, tell them they owe $5.99 If they chose cappuccino, tell them they owe $4.75 If they chose something else, tell them that the barista will be right there to help them

Your turn… If you have only a single line in your if/else statement, you can skip the curly braces!

What is the output of the following code? B C AB BC AC ABC Socrative

What is the output of the following code? Notice that “else” is optional. A B C AB BC AC ABC Without curly braces, only the first line is in the if-statement. The computer ignores indentation. Good indentation is just for people reading your code. Socrative

Both sides of the expression must be true for the AND to be true. Boolean Expressions We can use boolean operators to make more complex boolean expressions. Operator Name Example of use && And x > 7 && x < 17.5 x 7 17.5

Either side of the expression can be true for the OR to be true. Boolean Expressions We can use boolean operators to make more complex boolean expressions. Operator Name Example of use && And || Or x > 7 && x < 17.5 x < 5 || x > 15 x 5 15

NOT negates whatever the value is to make it the opposite. Boolean Expressions We can use boolean operators to make more complex boolean expressions. Operator Name Example of use && And || Or ! Not x > 7 && x < 17.5 x < 5 || x > 15 !(x > 3) x 3

De Morgan’s Laws x (x > 5 && x < 10) NOT does funny things with AND and OR. If we negate this… (x > 5 && x < 10) x 5 10

We suddenly take the opposite De Morgan’s Laws NOT does funny things with AND and OR. We suddenly take the opposite Which is equal to… !(x > 5 && x < 10) x 5 10

Likewise, !(x < 3 || x > 8) = !(x < 3) && !(x > 8) De Morgan’s Laws NOT does funny things with AND and OR. !(x > 5 && x < 10) !(x > 5) || !(x < 10) x 5 10 Likewise, !(x < 3 || x > 8) = !(x < 3) && !(x > 8)

Operator Precedence Operator Precedence Postfix expr++, expr-- Unary !, +, - Multiplicative *, /, % Additive +, - Relational >, >=, <, <= Equality ==, != Logical AND && Logical OR ||

Let’s play with this a little Ask the user for a number x If x > 7 AND x < 17.5 display “Nailed it!” Otherwise display “Too bad.”

Let’s play with this a little Ask the user for TWO numbers x and y If y is even, and x is between 1 and 10 inclusive, display “In Range” If y is odd, and x is less than 1 or greater than 10, display “In Range” Otherwise display “Out of Range” In your code, try to only write the words “In Range” ONE TIME. Use boolean operators to make this possible.

Let’s play with this a little Notice how we use parentheses to specify the precedence.

What does this evaluate to? Suppose x = 9 and y = 4 True False Socrative

What does this evaluate to? Suppose x = 9 and y = 4 True False Socrative

What does this evaluate to? Suppose x = 3 and y = 7 True False Socrative

What does this evaluate to? Suppose x = 3 and y = 7 True False Socrative

Another one Ask the user for three numbers: x, y, and z If x <= y <= z, display “In order!” Otherwise, display “Out of order” Notice that both sides of the boolean operator MUST BE complete boolean expressions!

Project Working in teams of up to size three: Program a Rock/Paper/Scissors game The computer should choose a random number between 0 and 2. Each number should correspond to rock, paper, or scissors. The user needs to choose rock, paper, or scissors. Compare the computer’s choice with the users choice and announce who won. Points will be given for style and readability

If expression matches value2, then control jumps here. Switch Statements Sometimes when you have a number of different cases, a switch statement is easier than if/else switch(expression) { case value1: statement-list1 break; case value2: statement-list2 … } If expression matches value2, then control jumps here.

Let’s do an example Ask the user for an integer to represent the month Use a switch statement to tell them what month corresponds with the number they chose.

If you forget the break statement, control falls through to the next case. If a number other than 1-12 is used, control gets sent to the default case.

What’s the output of the following code? B C D Something else Socrative

What’s the output of the following code? B C D Something else Since there are no break statements, control will fall through and this will output BCD Socrative