Loops and Expression Types

Similar documents
Branching and Boolean Expressions

Branching and Boolean Expressions

Arrays and Basic Algorithms

ANSWERS. Birkbeck (University of London) Software and Programming 1 In-class Test Feb Student Name Student Number. Answer all questions

Object-Oriented Programming in Java

Introduction Basic elements of Java

Section 002 Spring CS 170 Exam 1. Name (print): Instructions:

Java Coding 3. Over & over again!

H212 Introduction to Software Systems Honors

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Software and Programming 1

Input-Output and Exception Handling

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

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

JAVA OPERATORS GENERAL

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

ANSWERS. Birkbeck (University of London) Software and Programming 1 In-class Test Feb Student Name Student Number. Answer all questions

Loops. CSE 114, Computer Science 1 Stony Brook University

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

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

Prof. Navrati Saxena TA: Rochak Sachan

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

Birkbeck (University of London) Software and Programming 1 In-class Test Mar Answer ALL Questions

Programming with Java

Software and Programming I. Classes and Arrays. Roman Kontchakov / Carsten Fuhs. Birkbeck, University of London

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

St. Edmund Preparatory High School Brooklyn, NY

Lecture Set 4: More About Methods and More About Operators

ANSWERS. Birkbeck (University of London) Software and Programming 1 In-class Test Feb Student Name Student Number. Answer all questions

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

Object-oriented programming in...

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

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

CSI33 Data Structures

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

More on Objects and Classes

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

Over and Over Again GEEN163

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Software and Programming 1

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

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.

Lecture Set 4: More About Methods and More About Operators

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

PieNum Language Reference Manual

VENTURE. Section 1. Lexical Elements. 1.1 Identifiers. 1.2 Keywords. 1.3 Literals

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

3. Java - Language Constructs I

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

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

Chapter 3: Operators, Expressions and Type Conversion

Chapter 2 ELEMENTARY PROGRAMMING

Iteration statements - Loops

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

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

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

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

Place your name tag here

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

More on control structures

Introduction to Java & Fundamental Data Types

Repetition, Looping. While Loop

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Chapter 2 Elementary Programming

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

Introduction to Software Development (ISD) David Weston and Igor Razgon

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

CS 101 Spring 2007 Midterm 2 Name: ID:

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

Object-Oriented Programming

Fundamentals of Programming Data Types & Methods

AP CS Unit 3: Control Structures Notes

EXPRESSIONS AND ASSIGNMENT CITS1001

Chapter 2. Elementary Programming

CompSci 125 Lecture 11

Java+- Language Reference Manual

Chapter 3. Selections

CS212 Midterm. 1. Read the following code fragments and answer the questions.

Introduction to Programming Using Java (98-388)

COMPUTER APPLICATIONS

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Operators in java Operator operands.

Section 004 Spring CS 170 Exam 1. Name (print): Instructions:

AP COMPUTER SCIENCE A

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

A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern

Java Bytecode (binary file)

Arrays. Eng. Mohammed Abdualal

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

CS 112 Introduction to Programming

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

For that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

4 Programming Fundamentals. Introduction to Programming 1 1

CS 231 Data Structures and Algorithms, Fall 2016

9/18/11. Type casting, logical operators and if/else statement. Explicit Type Conversion. Example of Type Casting

switch-case Statements

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

int j = 0, sum = 0; for (j = 3; j <= 79; j++) { sum = sum + j; System.out.println(sum); //Show the progress as we iterate thru the loop.

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

Transcription:

Software and Programming I Loops and Expression Types Roman Kontchakov / Carsten Fuhs Birkbeck, University of London

Outline The while, for and do Loops Sections 4.1, 4.3 and 4.4 Variable Scope Section 5.8 Expressions and Types Operation Precedence SP1 2018-03 1

Boolean Variables and Operators The Boolean type boolean has two values, false and true three Boolean operators that combine conditions: && (and), (or),! (not) A B A && B false false false false true false true false false true true true A B A B false false false false true true true false true true true true A!A false true true false SP1 2018-03 2

Boolean Operators De Morgan s Laws:!(A && B) is equivalent to!a!b!(a B) is equivalent to!a &&!B NB: Java does not use mathematical notation: (in contrast to Python) if (0 <= temp <= 100) // ERROR - not an expression instead, use if (0 <= temp && temp <= 100) NB: and is NOT a Java operation SP1 2018-03 3

Conditional Operator conditional operator? : lets us write simple conditional statements as expressions 1 int actualfloor = (floor > 13)? floor - 1 : floor; is equivalent to 1 int actualfloor; 2 if (floor > 13) 3 actualfloor = floor - 1; 4 else 5 actualfloor = floor; an expression SP1 2018-03 4

The for Loop The for loop is normally used when instructions are executed repeatedly and a value runs from a starting point to an ending point with a constant increment (or decrement) initialisation (statement) condition (boolean expression) update (statement) 1 for (int i = 1; i <= 10; i++) 2 System.out.println("Hello, World!"); body: a block or a single statement SP1 2018-03 5

Assignment Operations shortcuts for increment and decrement: i++; is the same as i = i + 1; i--; is the same as i = i - 1; mixing operations and assignment: i += 2; is the same as i = i + 2; i *= 2.5; is the same as i = i * 2.5;... +=, etc. are of lowest precedence: i /= 2 + 3; is the same as i = i / (2 + 3); NB: ONLY assignment operators change values of variables (i - 1 does not!) SP1 2018-03 6

The for Loop: Example 1 public class PrintHelloWorld { 2 public static void main(string arg[]) { 3 for (int i = 1; i <= 10; i++) 4 System.out.println("Hello, World!"); 5 } 6 } Q: How many times is the phrase printed? SP1 2018-03 7

The for Loop: Example (cont.) Q: How many times is the phrase printed? 1 for (int i = 0; i < 10; i++) 2 System.out.println("Hello, World!"); 1 for (int i = 0; i <= 10; i++) 2 System.out.println("Hello, World!"); 1 for (int i = 10; i > 0; i--) 2 System.out.println("Hello, World!"); SP1 2018-03 8

The for Loop: Java v Python Java Python for(int i = 0; i < 10; i++) for i in range(0, 10) loop body is run with i set to 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 for(int i = 0; i < 10; i += 2) for i in range(0, 10, 2) loop body is run with i set to 0, 2, 4, 6, 8 for(int i = 10; i > 0; i--) for i in range(10, 0, -1) loop body is run with i set to 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 SP1 2018-03 9

The while Loop the while loop executes instructions repeatedly while a condition is true 1 final int RATE = 3; // 3% 2 while (balance < TARGET) { 3 year++; 4 double interest = balance * RATE / 100; 5 balance += interest; 6 } year balance 0 1000.00 1 1030.00 2 1060.90 3 1092.73 4 1125.51 SP1 2018-03 10

Loops and Assignments 1 int i = 6; 2 while (i >= 0) { 3 System.out.println(i - 1); 4 i = i - 2; 5 } i i >= 0 i - 1 i - 2 6 true 5 4 4 true 3 2 2 true 1 0 0 true -1-2 -2 false END OF THE LOOP SP1 2018-03 11

The for Loop initialisation (statement) condition (boolean expression) update (statement) 1 for (int k = 2; k <= 9; k++) { 2 String s = s0; 3 if (k % 2 == 1) 4 s = s1; 5 System.out.println(k + " is " + s); 6 } SP1 2018-03 12

... And the while Loop initialisation (statement) condition (boolean expression) update (statement) 1 int k = 2; 2 while (k <= 9) { 3 String s = s0; 4 if (k % 2 == 1) 5 s = s1; 6 System.out.println(k + " is " + s); 7 k++; 8 } SP1 2018-03 13

The do Loop the do loop is appropriate when the loop body must be executed at least once 1 Scanner in = new Scanner(System.in); 2 int value; 3 do { 4 System.out.println("Enter an integer < 100: "); 5 value = in.nextint(); 6 } while (value >= 100); NB: do not forget the semicolon ; at the end of the statement SP1 2018-03 14

Scope of a Variable The scope of a variable is the part of the program in which it is visible from its declaration until the end of the block, for a local variable the entire method of a method s parameter variable the for statement, for a local variable declared in a for statement Two variables can have the same name provided their scopes do not overlap SP1 2018-03 15

Scope: Example 1 What is wrong here? 1 public static int sumofsquares(int n) { 2 int sum = 0; 3 for (int i = 1; i <= n; i++) { 4 int n = i * i; 5 sum = sum + n; 6 } 7 return sum; 8 } SP1 2018-03 16

Scope: Example 2 What is wrong here? 1 Scanner in = new Scanner(System.in); 2 do { 3 System.out.println("Enter an integer < 100: "); 4 int value = in.nextint(); 5 System.out.println("Entered: " + value); 6 } while (value >= 100); SP1 2018-03 17

Boolean Expressions Suppose a is 5 and b is 4. What is the value of a > b? 1 public static boolean greater(int a, int b) { 2 return a > b; // returns true if a > b 3 } 1 boolean found = false; 2 while (!found) { 3... // do something 4 if (...) // if the condition is met 5 found = true; 6... // do something else 7 } SP1 2018-03 18

Expressions assignment statement cansperpack }{{} variable name = }{{} 8 ; expression an expression is a combination of variable names, literals, method calls and operators the type of an expression is known at compile-time: 8 is of type int 10.2 and -12.3e-45 are of type double "fooˆ=\nbar" is of type String (NB: Java s double corresponds to Python s float) false and true are of type boolean NB: types of variables are declared SP1 2018-03 19

Type Cast Operator Q: What is wrong with the following? 1 int income = 20000; 2 int tax = income * 0.13; corrected version: 2 int tax = (int) (income * 0.13); NB: do not forget brackets because type cast is of very high precedence Q: Would the following work? 2 int tax = income * (int)0.13; SP1 2018-03 20

Type Cast Operator Q: What is printed in the following fragment? 1 int a = 5, b = 2; 2 System.out.println(a / b); 1 int a = 5, b = 2; 2 System.out.println((double) a / b); SP1 2018-03 21

Operators and Expressions (1) suppose expr 1 and expr 2 are expressions of type boolean, double, int, or String the type of expr 1 + expr 2 is int if the type of both expr 1 and expr 2 is int double if the type of one of expr 1 or expr 2 is double and the other type is numerical, i.e., int or double String if the type of one of expr 1 or expr 2 is String otherwise, it is a compile-time error Q: what is the type of false + 1? similar rules apply to -, *, / and % except they are not defined on String SP1 2018-03 22

Operators and Expressions (2) suppose expr 1 and expr 2 are expressions expr 1 < expr 2, expr 1 <= expr 2, expr 1 > expr 2 and expr 1 >= expr 2 are of type boolean both expr 1 and expr 2 must be of numerical datatypes Q: what is the type of 60 <= marks <= 69? compile-time error otherwise expr 1 expr 2, expr 1 && expr 2 and! expr 1 are of type boolean both expr 1 and expr 2 must be of type boolean Q: what is the type of 60 <= marks && <= 69? compile-time error otherwise SP1 2018-03 23

Operation Precedence () method call highest!, (type) type cast, ++, -- unary *, /, % multiplicative +, - additive <, <=, >=, > relational ==,!= equality && logical AND logical OR?: conditional =, +=,... assignments lowest SP1 2018-03 24

Operation Precedence boolean f = 13 < floor - 1; is the same as boolean f = 13 < (floor - 1); Suppose we have the declaration: int a = 11; Evaluate the following expressions: 2 + a % 3 2 * 6 + a % 3 + 1 < 10 && a > 3 2 * 6 + a % 3 + 1 < 10 &&!a > 3 2 + a / 3 2 + (double) a / 3 SP1 2018-03 25

Loop Termination Collatz conjecture Lothar Collatz, 1937 { an /2, if a n is even The sequence a n+1 = eventually reaches 1 3a n + 1, if a n is odd 1 while (a > 1) { 2 if (a % 2 == 1) 3 a = 3 * a + 1; 4 else 5 a = a / 2; 6 } regardless of which positive integer a 0 is chosen SP1 2018-03 26

Take Home Messages The while loop executes instructions repeatedly while a condition is true The for is used when a value runs from a starting point to an ending point with a constant increment Variables can have the same name provided their scopes do not overlap SP1 2018-03 27