Week 4 - Monday CS 121.

Slides:



Advertisements
Similar presentations
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Advertisements

Week 4: Conditional Execution 1.  So far we have only considered Java programs that do one thing after another, in sequence  Our programs have not had.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 4 Making Decisions
C++ for Engineers and Scientists Third Edition
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Conditionals II Lecture 11, Thu Feb
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Agenda Exam #1 Review Modulus Conditionals Boolean Algebra Reading: Chapter Homework #5.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Rational Expressions and selection structures Relational operators Logical operators Selection structures.
Week 4 - Monday.  What did we talk about last time?  Wrapper classes  if statements.
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.
Chapter 4 Introduction to Control Statements Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else Statements Section 4.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
© The McGraw-Hill Companies, 2006 Chapter 2 Selection.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Week 3 - Wednesday.  What did we talk about last time?  Other C features  sizeof, const  ASCII table  printf() format strings  Bitwise operations.
What is a Boolean expression?
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.
Selection in C++ If statements. Control Structures Sequence Selection Repetition Module.
Control Statements: Part1  if, if…else, switch 1.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Week 3 - Friday.  What did we talk about last time?  Preprocessor directives  Other C features  sizeof, const  ASCII table  printf() format strings.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Discussion 4 eecs 183 Hannah Westra.
The Ohio State University
Java Programming Fifth Edition
The if…else Selection Statement
CS0007: Introduction to Computer Programming
COMP 14 Introduction to Programming
Week 3 - Friday CS222.
Chapter 4: Making Decisions.
Selections Java.
More important details More fun Part 3
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
Topics The if Statement The if-else Statement Comparing Strings
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,
Programming Fundamentals
Lecture 4: Conditionals
Topics The if Statement The if-else Statement Comparing Strings
Selection CIS 40 – Introduction to Programming in Python
Python - Conditional Execution
Conditions and Ifs BIS1523 – Lecture 8.
Scratch: selection / branching/ if / If…else / compound conditionals / error trapping by Mr. Clausen.
Java Programming Control Structures Part 1
The Java switch Statement
Boolean Expressions to Make Comparisons
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Winter 2019 CISC101 4/16/2019 CISC101 Reminders
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
CprE 185: Intro to Problem Solving (using C)
Using C++ Arithmetic Operators and Control Structures
Building Java Programs Chapter 4
Controlling Program Flow
IPC144 Introduction to Programming Using C Week 2 – Lesson 2
Presentation transcript:

Week 4 - Monday CS 121

Last time What did we talk about last time? if statements Lab 3

Questions?

Project 1

Conditional Execution Review

Conditional execution So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had the ability to choose between different possibilities Now, they will!

Behold! The if-statement: x is small will only print out if x is less than 5 In this case, we know that it is, but x could come from user input or a file or elsewhere int x = 4; if( x < 5 ) System.out.println("x is small!");

if( condition ) statement; Anatomy of an if Any boolean expression The if part if( condition ) statement; Any single executable statement

Conditions

Conditions in the if Any statement that evaluates to a boolean is legal Examples: x == y true Character.isDigit('r') s.equals("Help me!") && (z < 4)

Comparison The most common condition you will find is a comparison between two things In Java, that comparison can be: == equals != does not equal < less than <= less than or equal to > greater than >= greater than or equal to These are called relational operators

Equals You can use the == operator to compare any two things of the same type Different numerical types can be compared as well (3 == 3.0) Be careful with double types, 0.33333333 is not equal to 0.33333332 int x = 3; if( x == 4 ) System.out.println("This doesn't print");

Not Equals Any place you could have used the == operator, you can use the != operator If == gives true, the != operator will always give false, and vice versa If you want to negate a condition, you can always use the ! as a not is the same as if( x != 4 ) if( !(x == 4) )

= != == Remember, a single equal sign (=) is the assignment operator (think of a left-pointing arrow) A double equals (==) is a comparison operator int y = 10; if( y = 6 ) //compiler error! boolean b = false; if( b = false ) //no error but wrong

Less Than (or Equal To) Inequality is very important in programming You may want to take an action as long as a value is below a certain threshold For example, you might want to keep bidding at an auction until the price is greater than what you can afford Watch for strict inequality (<) vs. non-strict inequality (<=) if( x <= 4 ) System.out.println("x is less than 5");

Greater Than (or Equal To) Just like less than or equal to, except the opposite Note that (because of the All-Powerful Math Gods) the opposite of <= is > and the opposite of >= is < Thus, !( x <= y ) is equivalent to ( x > y ) !( x >= y ) is equivalent to ( x < y )

Else

Either/Or Sometimes you have to make a decision If a condition is true, you go one way, if not, you go the other For example: If I pass CS121, Then I throw a kegger to celebrate Otherwise, I punch Dr. Wittman in the face

Exclusivity Notice the nature of this kind of condition Both outcomes cannot happen Either a kegger gets thrown or Dr. Wittman gets punched in the face For these situations, we use the else construct

Two different outcomes Anatomy of an if-else if( condition ) statement1; else statement2; Two different outcomes

else example Scanner in = new Scanner(System.in); int balance = in.nextInt(); if( balance < 0 ) System.out.println("You are in debt!"); else System.out.println("You have $" + balance);

Multiple Statements and Nesting

What if you need to do several things conditionally? No problem Use braces to treat a group of statements like a single statement if( x == 4 ) { System.out.println("I hate 4"); System.out.println("Let's change x."); x = 10; }

An if with multiple statements if( condition ) { statement1; statement2; … statementn; } A whole bunch of statements

Nesting Sometimes you want to make one set of decisions based on another set of decisions if-statements can be nested inside the bodies of other if-statements You can put if-statements inside of if-statements inside of if-statements… going arbitrarily deep

Nested ifs if( condition1 ) { statement1; if( condition2 ) … }

An example using quadrants For the next example, recall the 4 quadrants of the Cartesian coordinate system y 2 1 (0,0) -x x 3 4 -y

Nesting example Find which quadrant the point (x,y) is in if( x >= 0.0 ) { if( y >= 0.0 ) System.out.println("Quadrant 1"); else System.out.println("Quadrant 4"); } System.out.println("Quadrant 2"); System.out.println("Quadrant 3");

if and else if You can list a sequence of exclusive possibilities using nesting: if( index == 1 ) System.out.println("First"); else if( index == 2 ) System.out.println("Second"); else if( index == 3 ) System.out.println("Third"); else System.out.println(index + "th");

else-if doesn’t actually exist A block of code is treated just like one statement A whole if-else is treated the same if( … ) statement1; else if( … ) statement2; else statement3; if( … ) { statement1; } else statement2; statement3; =

Pitfalls

Watch out! Now you are controlling the flow of execution in your program There is a wider range of mistakes you can make when giving instructions Huge chunks of code can be executed or skipped by mistake Here are a few things to watch out for

Empty statements Remember that an if-statement is not an executable statement It does not end with a semicolon if( balance < 0 ); // empty statement { // this block always runs System.out.println("You owe a fee!"); balance -= 15; }

Confusing indentation In some languages, indentation actually matters Java ignores whitespace "Fight!" prints no matter what if( enemies > 2 ) System.out.println("Run away!"); else defense = true; System.out.println("Fight!");

Imprecise conditions It’s easy to make logical errors when writing conditions If an airline allows two or fewer bags on the plane, someone might code that as: But this is too restrictive. It should be: if( bags < 2 ) // only allows 1 or 0 boarding = true; if( bags <= 2 ) boarding = true;

Reversed conditions Sometimes it’s easy to get a condition backwards Try not to assume you wrote the condition correctly Always double check if( number % 3 == 0 ) System.out.println("Not divisible by 3!"); else System.out.println("Divisible by 3!");

if Examples

Speed limit Sometimes you probably break the speed limit But, there's one speed limit you can never break The speed of light c is about 3 x 108 m/s Given a variable named speed of type double, what's an if-statement that will print an error message if speed is larger than c?

Upcoming

Next time… Examples switch statements

Reminders Keep reading Chapter 4 of the textbook Keep working on Project 1 (due this Friday) Exam 1 is next Monday