CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

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

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Text Input and Conditionals

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

Flow Control: Branches and loops

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

Overview. Iteration 4 kinds of loops. Infinite Loops. for while do while foreach

T H E I N T E R A C T I V E S H E L L

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

Types, Expressions, and States

CS1 Lecture 3 Jan. 18, 2019

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

CS1 Lecture 3 Jan. 22, 2018

Java Review. Fundamentals of Computer Science

Conditionals & Loops /

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Module 2: Choice and Iteration

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

5. Control Statements

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #17. Loops: Break Statement

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

Induction and Semantics in Dafny

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

CIS220 In Class/Lab 1: Due Sunday night at midnight. Submit all files through Canvas (25 pts)

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Get JAVA. I will just tell you what I did (on January 10, 2017). I went to:

Control Structures. Christopher Simpkins CS 3693, Fall Chris Simpkins (Georgia Tech) CS 3693 Scala / 1

Introduction to Python (All the Basic Stuff)

4.7 Approximate Integration

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

Lecture 8: Iterators and More Mutation

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

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

CS1 Lecture 5 Jan. 25, 2019

If you don t, it will return the same thing as == But this may not be what you want... Several different kinds of equality to consider:

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

Glossary. (Very) Simple Java Reference (draft, v0.2)

1.7 Limit of a Function

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

EXAM Computer Science 1 Part 1

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

Lecture 4 CSE July 1992

Shorthand for values: variables

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Lab 4: Super Sudoku Solver CSCI 2101 Fall 2017

CS1 Lecture 5 Jan. 26, 2018

FOR Loops. Last Modified: 01 June / 1

CS125 : Introduction to Computer Science. Lecture Notes #6 Compound Statements, Scope, and Advanced Conditionals

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

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while

Lecture Transcript While and Do While Statements in C++

COSC 122 Computer Fluency. Iteration and Arrays. Dr. Ramon Lawrence University of British Columbia Okanagan

Lesson 2.4 Arraylist

ECE 122. Engineering Problem Solving with Java

BM214E Object Oriented Programming Lecture 4

Introduction to Object-Oriented Programming

Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont)

Teaching guide: Subroutines

Repetition Through Recursion

Understanding Recursion

COMP combinational logic 1 Jan. 18, 2016

Lists of Lists. CS 5010 Program Design Paradigms Bootcamp Lesson 5.3

LOOPS. Repetition using the while statement

Instructor (Mehran Sahami)

Part 6b: The effect of scale on raster calculations mean local relief and slope

Appendix: Common Errors

(I m not printing out these notes! Take your own.)

Proofwriting Checklist

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

(Provisional) Lecture 08: List recursion and recursive diagrams 10:00 AM, Sep 22, 2017

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Grade 6 Math Circles November 6 & Relations, Functions, and Morphisms

AP Computer Science A

Linked Lists. College of Computing & Information Technology King Abdulaziz University. CPCS-204 Data Structures I

Lab 10: Sockets 12:00 PM, Apr 4, 2018

Repetition Structures

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Ch. 12: Operator Overloading

(Refer Slide Time 6:48)

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

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

In this lab, you will learn more about selection statements. You will get familiar to

QUIZ. Source:

Object-Oriented Programming

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

Table of Laplace Transforms

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Introduction to the Java Basics: Control Flow Statements

Introduction to Computation for the Humanities and Social Sciences. CS 3 Chris Tanner

Outline for Today CSE 142. Programming a Teller Machine. CSE142 Wi03 I-1. ATM Algorithm for Dispensing Money

Chapter 1 Getting Started

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Performing Matrix Operations on the TI-83/84

Transcription:

CISC-124 20180122 Today we looked at casting, conditionals and loops. Casting Casting is a simple method for converting one type of number to another, when the original type cannot be simply assigned to a variable of the target type. We cast the value to the desired type by putting that type in parentheses just to the left of the value. An example will show exactly what I am talking about: int x; double y = 1.999999999; x = y; // this would fail because we can t assign a double value to an int // variable x = (int) y; // this will work the value of y is converted to an int before // we assign it to x. Note that casting a real number to an integer truncates the number rather than rounds it. So in the example above x ends up with the value 1, even though y is very close to 2. Conditionals Conditionals are statements that let us choose between alternative actions. Of course we all know that the if statement handles this operation, so this section will be more of a review and an exploration of new ideas. In Java, if statements have a couple of slightly different flavours. This material should be very familiar from other languages so I ll just do some examples // example of single operation if { z = c*d; } // example of multiple operations

y = a b; // example of if... if (x == 4) y = a*b; if (x == 5) y = a/b; // example of chained or nested if if (x == 4) y = a*b; if (x == 5) y = a/b; y = a b; // example of chained or nested if with a final // The final is executed if all the boolean // expressions are false We had a very brief discussion about boolean expressions. Boolean expressions can be combinations of simpler expressions, for example if ( x == 3 && z == 4) Here the && means and. We will only execute the if both parts of the boolean expression are true. We can also use & for and (and this operator can also be applied to integers --- more about this later) The difference between && and & for and is that the && uses what we call lazy evaluation. Since the line only executes when both parts of the boolean expression are true, the && starts by evaluating just the first part ( x == 3 ). If this part is false we already know the won t be executed... so we don t need to evaluate the z == 4 part. Using lazy evaluation, Java just evaluates as much of the boolean expression as

it needs to. By contrast, & will always evaluate both sides. Lazy evaluation is a small optimization, but it is also an extremely useful programming tool. Suppose we want to take an action if the value in position 5 of an array is equal to 32. We could try something like this: if (myarray[5] == 32) but if myarray doesn t have a position 5 (ie myarray.length <= 5) then we will get an error. We can guard against this with if (myarray.length > 5) if (myarray[5] == 32) Now the second boolean expression is only tested if the array is long enough. Lazy evaluation simply lets us abbreviate this to if (myarray.length > 5 && myarray[5] == 32) We didn t discuss it in class, but there are two forms of or as well: and. As with the and operators, the first of these ( ) uses lazy evaluation.

There is another form of if that lets us embed the whole thing into a single statement. Consider this y = c*d; Both branches are just an assignment of a new value to the variable y. Java allows us to write this as y = x == 3? a + b : c*d; which looks completely incomprehensible, but everything after y = fits this template: boolean expression? value if the expression is true : value if the expression is false ; If you remember the Collatz sequence program we wrote, we could have replaced if (n%2 == 0) n = n/2; n = 3*n + 1; with n = n%2 == 0? n/2 : 3*n +1; It s shorter but harder to read. My advice: use with caution.

Java also provides a switch statement, which lets us evaluate an expression of almost any kind, then choose different actions based on its value. Here s a simple example: switch (x%6) { } case 0: case 2: default: z = c * d; break; y = a b; z = c + d; break; y = 124; z = 235; break; In this example, x is assumed to be an integer. The expression x%6 will have the value 0, 1, 2, 3, 4, or 5. Java chooses the appropriate instructions to execute. The default case is executed if none of the other cases match the value of the expression. Don t forget to include the break; at the end of each case. Without it, Java just keeps right on going and executes the instructions in the next case too.

Loops We have already seen the While loop, and there isn t much more to say about it. For loops in Java follow the standard C syntax: for (<initial situation> ; <continuation condition> ; <update>) {... } such as for (int i = 0 ; i < anarray.length ; i++) System.out.println(anArray[i]); If you haven t seen i++ before, it is just shorthand for i = i+1 Java also has a for each loop, which lets us iterate over all the values in a collection (for now, just think collection = array ). In a for each loop we define a temporary variable which is assigned each value in the collection, one after the other. for (int val : anarray) System.out.println(val); // assuming anarray is of type int[] produces exactly the same output as the previous for loop. We have seen break in the context of the switch statement. Java actually lets us use break to jump out of any control structure (if, while loop, for loop, etc.) When Java executes a break it jumps to the first line after the end of whatever it is breaking out of. This can be dangerous if over-used because it can make it difficult to follow our program flow, but it can also be very useful if used with caution. In general, you should not have more than one break statement in any control structure except the switch statement. It is entirely possible to code without using any break statements at all.

We also talked about the continue instruction. When executed in a loop, it doesn t break out of the loop but it ends the current iteration and begins the next one. for (int i = 1; i <= 10; i++){ } if (i%4 == 0) continue; System.out.println(i); This will print the values 1 2 3 5 6 7 9 10 The continue instruction is not necessary in any programming language but it can be convenient. You can see how the example just shown could be written without a continue.