COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Similar documents
COMP-202: Foundations of Programming. Lecture 6: Conditionals Jackie Cheung, Winter 2016

COMP-202: Foundations of Programming. Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016

Basics of Java Programming

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Chapter 3: Operators, Expressions and Type Conversion

Object-Oriented Programming

Building Java Programs

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

IEEE Floating-Point Representation 1

Lecture Set 4: More About Methods and More About Operators

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Chapter 3. Selections

CS 112 Introduction to Programming

CS 112 Introduction to Programming

COMP 202 Java in one week

COMP 202 Java in one week

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Operators. Java operators are classified into three categories:

Building Java Programs

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Chapter 2: Data and Expressions

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Building Java Programs

Chapter 2: Data and Expressions

Lecture 3 Operators MIT AITI

Lecture Set 4: More About Methods and More About Operators

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

Full file at

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

CEN 414 Java Programming

Programming with Java

Primitive data, expressions, and variables

Chapter 4: Control Structures I

COMP-202 Unit 4: Programming with Iterations

3. Java - Language Constructs I

Programming Lecture 3

Building Java Programs

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

ECE 122 Engineering Problem Solving with Java

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Chapter 2. Elementary Programming

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

Lesson 7 Part 2 Flags

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Unit 3. Operators. School of Science and Technology INTRODUCTION

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Conditional Programming

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

COMP 202. Java in one week

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Elementary Programming

JAVA OPERATORS GENERAL

Data Structure and Programming Languages

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

CMPT 125: Lecture 3 Data and Expressions

CS1150 Principles of Computer Science Boolean, Selection Statements

Prof. Navrati Saxena TA: Rochak Sachan

Topic 4 Expressions and variables

Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

4 Programming Fundamentals. Introduction to Programming 1 1

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Mr. Monroe s Guide to Mastering Java Syntax

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Building Java Programs Chapter 2

Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Accelerating Information Technology Innovation

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

COMP 110 Introduction to Programming. What did we discuss?

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Decisions (If Statements) And Boolean Expressions

Warm-Up: COMP Programming with Iterations 1

CS 231 Data Structures and Algorithms Fall Event Based Programming Lecture 06 - September 17, Prof. Zadia Codabux

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Algorithms and Conditionals

Object Oriented Software Design

Transcription:

COMP-202: Foundations of Programming Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Announcements Slides will be posted before the class. There might be few minor changes later. Extra class on the 20 th of May (13:05-15:25) at TR0100 Assignment 1 extended due date. New Due Date : 17 th of May (@ 23:30) Try all the exercises on the class slides. See me during office hours for any doubts and troubles solving them. Thanks for the responses on the survey.

Survey Results Can be a bit faster Good, slower is better Prefer more details Very helpful

Review Variables Data Types Strings User inputs

Review import java.util.scanner; public class SimpleInterest { // A program to compute Simple Interest public static void main(string[] args) { double principal, rateinterest; int yrs; Scanner inputreader = new Scanner(System.in); System.out.println( Enter the Principal Amount ); principal = inputreader.nextdouble(); System.out.println( Enter the Annual Rate of Interest ); rateinterest = inputreader.nextdouble(); System.out.println( Enter the number of years since loan ); yrs = inputreader.nextint(); double simpleinterest = (principal * rateinterest * yrs) / 100; System.out.println( Your simple interest after + yrs + years = + simpleinterest); } }

Data Types Review What data type and value do the following expressions evaluate to? (int) 5.67 + (3 / 2) (7 / 4) < (7.0 / 4.0) 25 + Hello ((int) 3.1 + 5) / 3.0

This Lecture Boolean Expressions Mathematical Expressions Flow Control One step at a time.

Expressions An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. An Expression has Operator acting on the Operands to generate a single valued result. int x = 5 + 10; String s = Hello + COMP202 ; The data type of the result depends both on the operator and the operands. An Expression is always evaluated from left to right, unless it is explicitly specified. There are exceptions depending on the precedence of the operator. We will see operator precedence later in the class.

Boolean Expressions

Boolean Expressions Boolean expressions evaluate to either true or false. mynumber > 0 // can be either true or false You can assign the result of a boolean expression to a variable of type boolean: boolean positive; positive = (mynumber > 0);

Boolean Expressions in Java A boolean expression is one of the following: Comparison of two values using a comparison operator like <. ( x < 5) true or false (Java's boolean literals these are keywords). A variable which has type boolean. (boolean x;) The result of a logical operator over other boolean variables.

Comparison Operators The result of a comparison is always true or false. Used to compare numeric or character values (remember ASCII?) == : equal to!= : not equal to < : less than > : greater than <= : less than or equal to >= : greater than or equal to

Examples int x = 5; x < 6 x <= 5 x > 5 x >= 3 x == 5 x!= 5 true true false true true false

Careful! Terrible things will happen if you mistype == as = int x = 5; int y = 3; (x = y); x is overwritten with the value of y, i.e. x=3 after this statement. This expression will return the value assigned to x, that will be int in this case not boolean (because, = is not a comparison operator). (x = = y); This sets check to false because x is not equal to y. This is the right way to compare. This expression will return a boolean (true or false).

Logical Operators These take boolean expressions as input, and produce a result of type boolean.! Logical NOT Logical OR && Logical AND They can have either one operand (unary), as in NOT, or two operands (binary), as in OR and AND.

! Operator The NOT operator flips the truth value of the boolean expression that follows. For an input boolean expression X: X!X true false false true

! Operator Examples!(2 < 3)!(3 < 2)!true!false!(!(3>2))!(September comes after August)!(Earth is the 6 th planet from the sun)

&& Operator The AND operator is true if both of the input boolean expressions evaluate to true. For input boolean expressions X and Y: X Y X&&Y true true true true false false false true false false false false

&& Operator Examples (1 < 2) && (2 < 3) (1 < 1) && (2 < 3) (!(1 < 1)) && (2 < 3) (Television starts with a T) && (Java can also be coffee) (true && false)

Operator The OR operator is true if at least one of the input boolean expressions evaluate to true. For input boolean expressions X and Y: X Y X Y true true true true false true false true true false false false

Operator Examples (1 < 1) (2 < 3)!((3 < 4) (100 > 1000)) ((Vegetables are healthy) (Fruit is healthy)) (true false)

Short-Circuit Evaluation The evaluation of && and stops as soon as you know the end result: If the left operand of && is false, the whole thing is false, so the second is never looked at. (p1 && p2) if p1 is false, p2 is never looked at. If the left operand of is true, the whole thing is true, so the second is never looked at. (p1 p2) if p1 is true, p2 is never looked at. This seems like a minor detail, but is important.

How This Is Useful Use the first part to check to make sure the second part can actually be run ((x!= 0) && ((1 / x) < 5)) This can be used to check if the program is trying to divide by zero.

Example Question Which of the following best describes the set of all pairs of values for boolean variables a and b, such that (!a && b) ==!(a b) evaluates to true? a) Empty set b) Only one pair: a == true, b == false c) Two pairs in which a == true d) Two pairs in which a!= b e) All four possible combinations of values ANSWER: ( C )

Mathematical Expressions

Mathematical Operators Some operators: Addition (+) Subtraction (-) Multiplication (*) Division (/) Remainder (a.k.a., modulo) (%) How these operators actually function depends on the data type of the operands.

+ Operator As seen already, int + int 3 + 4 7 (int) int + double (or double + int) 3 + 4.0 7.0 (double) Also defined for: String + String "3" + "4" "34" (String) String + primitive data type (or p.d.t. + String) 3 + "4" "34" (String)

-, * Operators Subtraction (e.g., 3-4) and multiplication work as you would expect. Like for +, if you mix ints and doubles, you get a double. But not defined for as many data types String * String ERROR

Integer Division If both operands to the division operator are int, the result is also an int (with the fractional part discarded) 11 / 3 3-11 / 3-3 Division by 0 with integers causes a runtime error. Not detected at compile time! 1 / 0 CRASH

% Modulo Operators Modulo operator gives the remainder of a division. Example: 5 % 3 2 4 % 2 0 1234 % 100 34

Operator Precedence 1. Parenthesis 2. Casting 3. *, /, % from left to right 4. +, -, from left to right Assignment happens after the evaluation of the expression. To reduce ambiguity and to make your life easy, always use parenthesis.

Operator Precedence Few Examples: 1.0 / 2 4 / 3 + 4.0 / 3 (double) 1 / 2 (double) (1 / 2) ( 1 + 2 ) * 3 1 + 2 * 3 You can learn more on operator precedence at: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/oper ators.html

+=, ++ (shorthand operators) Programmers got lazy about writing x = x + 5; So, as a shortcut, you can write!! x += 5; Then they got even lazier about writing x += 1; So, as a short, you can write x++;

-=, *=, /=, -- Similarly: x -= 5; is the same as x = x - 5; And likewise for *=, /=. Also, x--; is the same as x -= 1; or x = x - 1;

++, -- (Increment Operator) You can put ++ or -- before or after a variable name, and even as part of a complex expression. After (post increment) x++: use and then increment. Before (pre increment) ++x: increment and then use. int x = 5, y = 5; System.out.println(x++); System.out.println(++y);

Recommendation Only use ++ or -- by themselves, and do not put them inside other expressions. int x = 5; int y = 2 * x++ + 4; // legal, but confusing Other shorthand operators are not very useful and are not seen in general programming practices.

Example Question 1) What is the output? int i = 10; int n = i++; System.out.println( Value i = + i + and n = + n); Answer: Value i = 11 and n = 10 2) What is the output? int i = 10; i++; int n = i; System.out.println( Value i = + i + and n = + n); Answer: Value i = 11 and n = 11

Try it out Write a program that takes a 3-digit number and checks if the digits are in ascending order. For example: If the input is 321, your program should output true. If the input is 213, your program should output false. Hint: break it down into the following steps: 1. Set up main method in a class 2. Get the Scanner working 3. Separate every digit of the number (as in unit place, ten s place, hundred place) 4. Use Boolean expressions to generate the required result.

Conditionals (Testing)...

Control Flow Up to this point, our programs proceed in a "straight" fashion. Just follow each line of code in the main method There are commands that can decide if a particular block of code needs to be executed or not. These commands refer to the control flow because you control where the program execution goes next.

Control Flow 1. if statements 2. if-else statements 3. if-else if-else statements 4. while loops 5. for loops

if and if-else if (<condition>) { <body statements 1> } if (<condition>) { <body statements 1> } else { <body statements 2> }

( if ) and (if-else)

Example Example: Print different things depending on what the String we are given is. Scanner scanner = new Scanner(System.in); String languagechoice = scanner.nextline(); if (languagechoice.equals("english")) { System.out.println("You chose English."); } else { System.out.println("You chose non-english."); }

Structure of a Conditional if (languagechoice.equals("english")) { System.out.println("You chose English."); } else { System.out.println("You chose non-english."); } The condition to check (make sure it is surrounded by parentheses)

Structure of a Conditional if (languagechoice.equals("english")) { System.out.println("You chose English."); } else { System.out.println("You chose non-english."); } The block of code executes if the condition evaluates to true.

Structure of a Conditional if (languagechoice.equals("english")) { System.out.println("You chose English."); } else { System.out.println("You chose non-english."); } The second block of code gets evaluated if the condition evaluates to false. If there is no else block, no extra code block is run.

if-if vs. if-else What is the difference? if (condition) { //some commands here } if (not condition) { //more commands here } if (condition) { //some commands here } else { //more commands here } Both blocks on the left could execute, if at the end of the first block, (not condition) somehow becomes true.

Going Into Two if Statements int x = 1; if (x > 0) { System.out.println("Positive. Altering the value."); x--; } if (x <= 0) { System.out.println("Not positive"); }

Only One Branch Executes int x = 1; if (x > 0) { System.out.println("Positive. Resetting value."); x--; } else { System.out.println("Not positive"); }

if - else if - else For when you have a more complicated set of conditions with more than two options. Option 1: Nested if-else statements if (condition 1) { } else { } if (condition 2) { } else { } if (condition 3) { }

Better Way (else if) Option 2: All at the same level if (condition 1) { } else if (condition 2) { } else if (condition 3) { } else { }

if - else if - else

Order Matters Much like else, the "else if" is only entered if the prior conditions were false. So, there can be a big difference if the order of the options are changed.

What Is Wrong Here? if (money > 0.0) { System.out.println("Positive balance"); } else if (money > 1000.0) { System.out.println("You're rich!"); } else { System.out.println("Uh-oh."); } What happens if the variable money = 1200?

Omitting Curly Braces A dangerous game. if (x < 0) System.out.println("x is less than zero."); System.out.println("x is definitely negative."); Remember that Java ignores the indentation, so this is very misleading!

Example Question 1) What will be the value of x after the following section of code executes: int x = 5; if (x > 3) x = x 2; else Answer: B x = x + 2; A. 1 B. 3 C. 5 D. 7 2) What will be the value of b after the following section of code executes: int a = 4, b = 0; if (a < 3) b = 4; else if ( (a < 10) && (b>0) ) b = 3; else if ( (a > 5) (b==0) ) Answer: C b = 2; else b = 1; A. 1 B. 0 C. 2 D. 4

Try it out!! Extend your previous program to convert temperatures. 1. Now, it first asks if the user wants to convert from Fahrenheit to Celsius. 2. If the user replies "true", it works as before. 3. Otherwise, it converts from Celsius to Fahrenheit.

Try it out!! Read three positive integers x, y, and z from the user and report the maximum and the minimum integers.

Summary Boolean Expressions Mathematical Expressions Conditional Statements if if else if else if