Computer Science 202 Introduction to Programming The College of Saint Rose Fall Topic Notes: Conditional Execution

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

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

5. Selection: If and Switch Controls

SELECTION. (Chapter 2)

Course PJL. Arithmetic Operations

Full file at

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Control Structures in Java if-else and switch

CS 106 Introduction to Computer Science I

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

3. Simple Types, Variables, and Constants

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

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

5. Control Statements

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

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Topics. Chapter 5. Equality Operators

Chapter 3: Decision Structures

CS313D: ADVANCED PROGRAMMING LANGUAGE

conditional statements

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

4. Java Project Design, Input Methods

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++.

Introduction to Computers and Engineering Problem Solving 1.00 / Fall 2004

Control Structures in Java if-else and switch

CSC Java Programming, Fall Java Data Types and Control Constructs

Chapter 3: Decision Structures

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

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.

ECE 122 Engineering Problem Solving with Java

Chapter 2: Using Data

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

Chapter 3: Decision Structures

CIS202 Exam 1 1. Convert from base 2 to base 10 (4 points)

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

Chapter 2. C++ Basics

Bits, Words, and Integers

Full file at

Chapter 4: Control Structures I

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

CS 106 Introduction to Computer Science I

Introduction to Programming Using Java (98-388)

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

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

CST141 Thinking in Objects Page 1

Computers and FORTRAN Language Fortran 95/2003. Dr. Isaac Gang Tuesday March 1, 2011 Lecture 3 notes. Topics:

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Intro. Scheme Basics. scm> 5 5. scm>

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

CSCI 355 Lab #2 Spring 2007

Review. Relational Operators. The if Statement. CS 151 Review #4

CSCI 355 LAB #2 Spring 2004

CS 115 Lecture 8. Selection: the if statement. Neil Moore

H212 Introduction to Software Systems Honors

MICROPROCESSORS A (17.383) Fall Lecture Outline

Today in CS161. Lecture #7. Learn about. Rewrite our First Program. Create new Graphics Demos. If and else statements. Using if and else statements

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

C++ Reference NYU Digital Electronics Lab Fall 2016

The following expression causes a divide by zero error:

Eng. Mohammed S. Abdualal

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

Module 2: Choice and Iteration

Lecture Transcript While and Do While Statements in C++

Today in CS161. Week #3. Learn about. Writing our First Program. See example demo programs. Data types (char, int, float) Input and Output (cin, cout)

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

First Java Program - Output to the Screen

Chapter 3: Operators, Expressions and Type Conversion

Software Design & Programming I

APCS Semester #1 Final Exam Practice Problems

Introduction. C provides two styles of flow control:

Conditions and Logical Expressions. C Programming

Chapter 3. Selections

Lecture 5 Tao Wang 1

CSCI 131, Midterm Exam 1 Review Questions This sheet is intended to help you prepare for the first exam in this course. The following topics have

CS 106 Introduction to Computer Science I

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Boolean Expressions. Is Equal and Is Not Equal

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Boolean Expressions. Is Equal and Is Not Equal

Chapter 3: Arrays and More C Functionality

Chapter 4 - Notes Control Structures I (Selection)

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION

Module 1: Types and Expressions

CS 106 Introduction to Computer Science I

UIC. C Programming Primer. Bharathidasan University

Information Science 1

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

QUIZ: What value is stored in a after this

Transcription:

Computer Science 202 Introduction to Programming The College of Saint Rose Fall 2012 Topic Notes: Conditional Execution All of our programs so far have had one thing in common: they are entirely sequential. The statements in our main methods all execute, one after another, in the order they are encountered in our program. While this is useful in many cases, we would like to move beyond that and have our programs start to make choices. We would like to be able to check for a certain condition. If the condition is true we would like to do one thing, if it s false we would do something else or possibly nothing at all. Thinking of every day algorithms, this is something we do all the time. If I am still hungry, I will go for seconds. If it is a weekday, I will set my alarm to get up for class. Otherwise, I will sleep as long as I would like. If the dough is too watery, add more flour. If the student s score is at least 95% on the spelling test, put a sticker at the top. Visual Logic s If Condition We will begin our exploration of this idea with Visual Logic, using the If Condition. We will develop a small program that asks what year you were born, and prints out a message that depends on that. In the If Condition in Visual Logic, we can specify a boolean condition something that evaluates to either true or false and depending on that result, the execution will continue on one of two paths. Our program will print out your age, and an extra message if you were born before 1995 (when Java was born). Java s if Statement Java has a construct that does the same thing. We will look at a simplified version first: one that either does something or not. The basic form is

if (<boolean condition>) { statement1; statement2; where <boolean condition> is some Java expression that evaluates to true or false. If it evaluates to true, the statements inside the curly braces following the condition are executed. Otherwise, they are skipped. Let s use this to develop our program. See Example: OlderThanJava There are many things that can be used to construct a boolean expression, but we will start with the standard relational operators and use them to compare numeric values. Expression x > y x < y x >= y x <= y x == y x!= y When is it true? when x is greater than y when x is less than y when x is greater than or equal to y when x is less than or equal to y when x is equal to y when x is not equal to y Java s if-else Construct The if statement we saw above allows us to execute a statement or group of statements if the condition is true. Often, we want to execute one set of statements if the condition is true and another set if the condition is false. In Visual Logic, we can do this by placing flowchart symbols on the false side of the If Condition symbol as well as on the true side. We will expand our OlderThanJava program to do this. Here, we print a different message if the person is younger than or the same age as Java (in addition to the previous message when the person is older). In Java, we can use the if-else construct. if (<boolean condition>) { statement1a; statement1b; else { 2

statement2a; statement2b; where <boolean condition> is some Java expression that evaluates to true or false. See Example: OlderYoungerThanJava Another Example, Adding in JOptionPane I/O We will next consider another example of if statements in Java, but with the added bonus of using a different mechanism for input and output. The problem: we wish to write a program that calculates the number of full payments needed for a no-interest loan where we are given a loan amount and desired monthly payment. This number is reported. If additional funds are due after those full payments are made, that is reported as well. See Example: NoInterestLoan The comments in that example describe in detail three new items: The use of JOptionPane.showInputDialog to bring up a dialog box with a message and a text box for input, and returning the text typed into the box as a String. The use of Java s Integer.parseInt method to convert a String to an int, which is necessitated here because the JOptionPane.showInputDialog only returns String values. The use of Java s JOptionPane.showMessageDialog to bring up a dialog box to display some program output. Nested Conditionals There is nothing stopping us from putting conditionals inside of conditionals. Consider this decision-making problem of whether it s a good idea to cancel classes tomorrow so we can go skiing. Suppose we are only willing to go skiing if the temperature will be no higher than 50 and there is at least 6 inches of snow on the ground in the mountains. We will first build a Visual Logic flowchart for this. We can ask either of the questions (temperature or snow cover) first, and if that response doesn t disqualify the day as a ski day, only then will we ask the other. Let s ask temperature first, then if the temperature is cool enough, ask about the snow cover. 3

All we really need to understand here is that any flowchart element, including an If Condition, can be placed on one of the branches of the If Condition. See Example: ShouldWeSki When we convert this to Java, we will place prompt that reads in and the entire condition that checks for a deep enough snow cover within the if part (the part that happens if the temperature is below 50). Java s if-else-if Construct Our next example is a program that asks for the user s name and hometown, then displays a message that indicates whether the length of (number of characters in) the name is more than, less than, or the same as the length of the town. Again, we can construct a Visual Logic flowchart. We know most of what we need to do this, the exception being how we can compute the length of a string. In Visual Logic, we can compute the length of a string (if it s called s) with length(s) We can then use the number returned as part of our condition to decide which branch of an If Condition we should take. Note that there are 3 possible cases: the name is shorter, the town is shorter, or they are the same length. Since an If Condition only has two choices, we will need more than one If Condition. See Example: NameAndTown For this conversion to Java, we could do a nested if as we did for the previous example. However, there is a variant on the if-else construct that allows us to check multiple conditions in a sequence and (optionally) perform an otherwise case at the end. It is sometimes called the if else-if construct, and looks like this: if (cond1) { // cond1 true stuff else if (cond2) { // cond2 true stuff (only can happen if cond1 false) else if (cond3) { // cond3 true stuff (only can happen if cond1 and cond2 false) else if (condn) { 4

// condn true stuff (only can happen if all previous conds false) else { // "otherwise" -- will happen if all previous conds false In our program we can see that construct where we first check if the name is shorter. If not, we check if the name is longer. If neither was true, then they must have been equal in length, so the final else is executed. Also notice that we also have a mechanism in Java to compute the length of a String. So far, we have made use of only a fraction of the capabilities of Java s String class. All we have done is to declare variables capable of holding String references, assign String values to them, and use those values in constructing outputs. There are many methods provided by Java s Strings and we will see a lot of them in coming weeks. For now, we just need the one that can give us a String s length. If we have a String in a variable s, we can compute its length with s.length(); With this available to us, we can complete the example program. Boolean data and boolean expressions Our discussion of conditional execution needs to include a look at more complex boolean expressions. The common boolean expression operators are arithmetic comparisons: == to test for equality,!= to test for inequality, and the inequality tests: <, <=, >, and >=. &&, which is the and operator. Its result is true if both of its operands evaluates to true., which is the or operator. Its result is true if either of its operands evaluates to true.! which evaluates to the boolean opposite of its only operand. We will encounter all of these in meaningful examples going forward, but for now, we can see many of them in action in this example. See Example: BooleanDemo See the comments therein to see some details. 5

In particular, note the precedence of these operators: && is evaluated before, much like multiplication is evaluated before addition in an arithmetic expression. Important note: you need to be very careful that you do specify these operators as && and rather than & and. The single-character operators will perform a bitwise and (or) rather than a logical and (or), which is not usually what you want.. Armed with these constructs and a few more we will see in this example, we can now tackle a more complicated problem. See Example: MassPikeTolls The comment at the top of the Java program describes the problem. This is a complex enough decision problem that we should first sketch out a flowchart in Visual Logic. We will need to use the boolean operators in Visual Logic, which are a bit different: arithmetic comparisons: = to test for equality, <> to test for inequality, and the inequality tests: <, <=, >, and >=. AND, which is the and operator. Its result is true if both of its operands evaluates to true. OR, which is the or operator. Its result is true if either of its operands evaluates to true.! which evaluates to the boolean opposite of its only operand. We end up with 3 possible outputs: There is a full toll if both entry and exit were at an interchange numbered 6 or higher, or if we are driving a truck. There is no toll if both entry and exit were at an interchange numbered 6 or lower, and we are not driving a truck. There is a toll on only part of the trip (east of interchange 6) if we entered or exited on one side of interchange 6 See the comments throughout the Java program for more information. Note in particular these new Java methods and constructs: The use of System.exit(1) to terminate the program when an error occurs (in this case, an invalid input was encountered). The use of a more complex form of JOptionPage.showMessageDialog to more clearly indicate an error message as opposed to an informational message like those we have used previously. 6

The use of the String s equals method to compare String values. We cannot use == to compare Strings for equality in most cases. Java will accept it, but it does not have the meaning we wish it to have in this context. More on this later in the semester. The switch Statement A common pattern in programming is to have a series of statements of the form: if (x == 0) { // do stuff for x == 0 else if (x == 1) { // do stuff for x == 1 else if (x == 2) { // do stuff for x == 2 else if (x == 8) { // do stuff for x == 8 else { // do stuff when x is none of the above Let s look at an example where this occurs. Consider a program that tells you which Computer Science faculty member you can find in each of the offices in the Albertus 400 suite. See Example: CSOfficesIfElse Java (and many other languages) provide a special construct we can use in situations like this that can be a bit more convenient. switch (x) { case 0: // do stuff for x == 0 case 1: // do stuff for x == 1 case 2: // do stuff for x == 2 7

case 8: // do stuff for x == 8 default: // do stuff when x is none of the above This works only when the comparison if for equality and we are using one of these data types: char, byte, short, or int. So far, we have only used int variables from among this group. Note that it does not work for double or String values. Also note that each case is ended by a special statement: If we rewrite the example to use a switch statement, it would look like this: See Example: CSOfficesSwitch If we mistakenly leave out a statement, Java will fall through to the next case. Sometimes this is handy and just what we want, but the vast majority of the time, we want a at the end of case case. One situation where this does come in handy is when we want to do the same thing for multiple cases: See Example: LittlePrimes Formatting Output Our next example has more conditionals, but also shows how we can nicely format output that contains floating point numbers. See Example: Payroll The key points to notice from this example: The use of named constants for numbers that are unlikely to change from one execution of the program to the next. The declaration of variables that will be assigned inside the if-else before the if-else. If they were defined within the body of the if parts and/or else part, those variables would exist only within those blocks of code. The declaration, construction, and use of DecimalFormat objects to format our floatingpoint output. See the text for more examples. The essentials: Like Scanner and JOptionPane, we need to tell Java if we intend to use a DecimalFormat with 8

import java.text.decimalformat; Before we make use of one, we need to declare a variable of type DecimalFormat and construct an instance. The parameter we pass to this constructor is the number of digits and any other characters we want. There are two examples in this proram, more in the text. When we want to print out a floating point value as formatted by one of these DecimalFormat objects, we pass the floating point value to the object s format method. This returns a String representation of that value using the specified format. 9