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

Similar documents
Controls Structure for Repetition

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

First Java Program - Output to the Screen

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

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

JAVA OPERATORS GENERAL

Building Java Programs

Full file at

Operators in java Operator operands.

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

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Building Java Programs

CEN 414 Java Programming

Building Java Programs

COMP 202 Java in one week

CSE 142, Summer 2014

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Lesson 7 Part 2 Flags

Chapter 4: Control Structures I

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

Handout 4 Conditionals. Boolean Expressions.

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

Algorithms and Conditionals

Chapter 3: Operators, Expressions and Type Conversion

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

Chapter 3. Selections

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

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

CSE 142, Summer 2015

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

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

More Programming Constructs -- Introduction

AP Computer Science Unit 1. Programs

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

CMPT 125: Lecture 4 Conditionals and Loops

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Topic 4 Expressions and variables

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

Introduction to Computer Programming

Data Structure and Programming Languages

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

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

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

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

Loops. CSE 114, Computer Science 1 Stony Brook University

Chapter 3 Selection Statements

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

Chapter 2. Elementary Programming

Basics of Java Programming

Lecture 3 Tao Wang 1

BRANCHING if-else statements

Basic Programming Elements

Fundamentals of Programming Data Types & Methods

Flow Control. Boaz Kantor Introduction to Computer Science, Fall semester IDC Herzliya

DM550 Introduction to Programming part 2. Jan Baumbach.

Conditional Programming

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

6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions

COMP Primitive and Class Types. Yi Hong May 14, 2015

Visual Programming. Lecture 3: Loops, Arrays. Mahmoud El-Gayyar

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

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Selenium Class 9 - Java Operators

CONDITIONAL EXECUTION

Example: Monte Carlo Simulation 1

Chapter 3, Selection. Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved.

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Oct Decision Structures cont d

CompSci 125 Lecture 11

Java Basic Programming Constructs

Control Structures: if and while A C S L E C T U R E 4

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

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

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

CSE 114 Computer Science I

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #06 Loops: Operators

Flow Control. Key Notion. Statement Categories. 28-Oct-10

CS 101 Exam 2 Spring Id Name

Topics. Chapter 5. Equality Operators

4. Number Representations

Lecture 6. Drinking. Nested if. Nested if s reprise. The boolean data type. More complex selection statements: switch. Examples.

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Computer Components. Software{ User Programs. Operating System. Hardware

3. Java - Language Constructs I

Chapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type

Computer Science II Lecture 1 Introduction and Background

CONDITIONAL EXECUTION

Darrell Bethea May 25, 2011

Data Structure and Programming Languages

Flow Control. So Far: Writing simple statements that get executed one after another.

Control Structures in Java if-else and switch

Give one example where you might wish to use a three dimensional array

b. Suppose you enter input from the console, when you run the program. What is the output?

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

CS111: PROGRAMMING LANGUAGE II

Mr. Monroe s Guide to Mastering Java Syntax

4. Java Project Design, Input Methods

Transcription:

Boolean Expressions Now we have the ability to read in some information, calculate some formulas and display the information to the user in a nice format. However, the real power of computer programs lies in their ability to make decisions. If a computer program always executed the same exact way, it would be quite boring. Rather, we can do much more if we have choices to make, and based on those choices, can execute different lines of code. An if statement allows us to do this. Before we get into the syntax of an if statement, we must discuss Boolean expressions. A Boolean expression is an expression that evaluates to true or false. For example, five is equal to two is an expression. Since we know that five equals five and not two, this expression evaluates to false. A simple Boolean expression is one that compares two values with an equality operator or a relational operator. Here is a list of both equality and relational operators: Operator Meaning == equal!= not equal > greater than < less than >= greater than or equal to <= less than or equal to So, for example, here are the results of several simple Boolean expressions: Boolean Expression Result (35 7) < 28 FALSE 3 + 2*8 > 18 TRUE 88 == 33 + 55 TRUE 24!= 4*3*2*1 FALSE In general, a simple Boolean expression has the following syntax: <arithmetic expr.> <relational or equality operator> <arithmetic expr.>

Any of the fairly simple arithmetic expressions in the examples above can be replaced with more complex and meaningful expressions that contain variables and often operators themselves. Boolean Operators We can also form more complex Boolean expressions out of simple ones through Boolean operators. There are two common binary Boolean operators and one unary one. A binary operator is one which takes two operands while an unary operator takes only one operand. Boolean operator Meaning && and or! not For the binary Boolean operators, the general syntax is as follows: <Boolean expression> <Boolean operator> <Boolean expression> The result of this Boolean operation is also Boolean (i.e. the result is true or false.) Here are truth tables showing the result for each of these three operands: && TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE TRUE FALSE TRUE TRUE TRUE FALSE TRUE FALSE! TRUE FALSE FALSE TRUE Thus, an and operation is only true if BOTH Boolean expressions involved are true. But, an or operation is true if at least one of the Boolean expressions involved is true. Finally, the not operation negates the value of a

Boolean expression. Once again it will be instructive to look at a few examples: Complex Boolean Expression Value (8 > 7) && (3 2!= 1) FALSE (4*3 <= 12) (2 > 100) TRUE!(88 == (22 + 66)) FALSE

If statement Now we are ready to see the if statement. The if statement allows you to execute a segment of code ONLY IF a particular Boolean condition is true. Here is the general syntax of an if statement: if (<boolean expression>) stmt; So, for example, here is a segment of code which prints out, Let s go to the beach, if the temperature is greater than 80 degrees. (Assume that the variable temperature stores the current temperature in Fahrenheit.) if (temperature > 80) System.out.println( Let s go to the beach. ); Now, it is possible that we may want to execute more than one statement inside an if statement; we may want to play Frisbee if it is greater than 80 degrees outside. To include this idea, we must introduce a block of code. A block of code is designated by matching braces({). Here is an example utilizing this idea: if (temperature > 80) { System.out.println( The temperature is + temperature + degrees F. ); System.out.println( Let s go to the beach. ); System.out.println( Let's play Frisbee. ); The braces indicate that everything inside of them are to be treated as the statement inside of the if. To illustrate this, a standard programming convention is to indent everything inside of the block of code uniformly, lining up the closing brace with the beginning if. We will talk more about indenting later, but the main rule you must follow is to indent everything inside of a block of code uniformly. (Notice that you also indent if there is a single statement inside of an if.) Also, you might imagine that if the Boolean expression in question is not true, we may want to follow a different course of action. Most people enjoy the beach when it is warm outside. An if statement allows us to do

something else instead of going to the beach with an else clause. Here is the general syntax: if (<boolean expression>) stmt1; else stmt2; In this construct, if the Boolean expression is true, only stmt1 gets executed, but if it is false, then stmt2 gets executed. Here is an example of such a statement: if (temperature > 80) { System.out.println( The temperature is + temperature + degrees F. ); System.out.println( Let s go to the beach. ); System.out.println( Let's play Frisbee. ); System.out.println( It is chilly outside. ); System.out.println( Therefore we must study for our Java class. ); There are a couple other variants of the if statement which we will see in the next lecture. But, for now, let s look at examples of code implementing if statements. 1) Write a program that prompts the user for a year and determines if it is a leap year or not, printing this information to the screen. Here are the rules for a leap year: 1) It must be divisible by 4 2) It can not be divisible by 100, unless it is also divisible by 400 Here is the program: // LeapYear.java // This program prompts the user to enter a year and determines if it is a leap

// year or not. public class LeapYear { public static void main(string args[]) { Scanner stdin = new Scanner(System.in); // Read in year from user. int year; System.out.println( Enter a year. ); year = stdin.nextint(); // Consider case where year is divisible by 4. if ( year%4 == 0) { // Check for exception to the divisible by 4 rule. if (year%100 == 0 && year%400 == 0) { System.out.println(year + is a leap year. ); System.out.println(year + is not a leap year. ); System.out.println(year + is not a leap year. ); Now we will look at a slightly easier example. The following program lets the user convert a temperature from Fahrenheit to Celcius or vice versa: // TempConv.java // This program will let the user either convert a celsius value to a fahrenheit // one, or the other way around.

public class TempConv { public static void main(string args[]) { Scanner stdin = new Scanner(System.in); char answer; double fahr,cel; // Read in user s choice of conversion. System.out.println( To convert Celsius to Fahrenheit enter a. ); System.out.println( To convert Fahrenheit to Celsius enter b. ); answer = (stdin.next()).charat(0); // Execute appropriate section of code, based on user s choice. if (answer = a ) { System.out.println( Enter a temperature in Celsius. ); cel = stdin.nextdouble(); // Calculate conversion and print out result. fahr = 32 + 1.8*cel; System.out.println(cel + Celsius is + fahr + Fahrenheit. ); System.out.println( Enter a temperature in Fahrenheit. ); fahr = stdin.nextdouble(); // Calculate conversion and print out result. cel = (fahr 32)*5/9; System.out.println(cel + Celsius is + fahr + Fahrenheit. );