Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Similar documents
Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Example: Monte Carlo Simulation 1

Nested Loops. A loop can be nested inside another loop.

Exercise (Revisited)

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

switch-case Statements

Arithmetic Compound Assignment Operators

Arithmetic Compound Assignment Operators

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

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

++x vs. x++ We will use these notations very often.

IEEE Floating-Point Representation 1

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

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

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

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

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

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

1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207

Variable Scope. The variable scope is the range of the program where the variable can be referenced.

Introduction to Programming Using Java (98-388)

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

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

Midterm Examination (MTA)

Fundamentals of Programming Data Types & Methods

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.

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

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

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

Introduction to Java & Fundamental Data Types

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

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

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

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

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

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

CS 211: Methods, Memory, Equality

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Array. Array Declaration:

Flow Control. CSC215 Lecture

PROGRAM EFFICIENCY & COMPLEXITY ANALYSIS

Object Oriented Programming. Java-Lecture 6 - Arrays

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

Algorithm. Algorithm Analysis. Algorithm. Algorithm. Analyzing Sorting Algorithms (Insertion Sort) Analyzing Algorithms 8/31/2017

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

Arrays. Eng. Mohammed Abdualal

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Recursion 1. Recursion is the process of defining something in terms of itself.

CS141 Programming Assignment #5

Zheng-Liang Lu Java Programming 45 / 79

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

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

PROGRAMMING FUNDAMENTALS

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

The return Statement

Values in 2 s Complement

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

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

ECE 122. Engineering Problem Solving with Java

Lecture 5: Methods CS2301

Chapter 2: Complexity Analysis

Controls Structure for Repetition

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Program Control Flow

Program Control Flow

How to swap values of two variables without tmp? However, this naive algorithm is biased. 1

Last Class. While loops Infinite loops Loop counters Iterations

CS1150 Principles of Computer Science Loops (Part II)

Example. Password generator

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

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

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

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

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

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

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226

1 Short Answer (10 Points Each)

Example: Fibonacci Numbers

Instructor: Eng.Omar Al-Nahal

Object Oriented Software Design

Problem Solving With Loops

Expressions & Flow Control

CS111: PROGRAMMING LANGUAGE II

CEN 414 Java Programming

Programming refresher and intro to C programming

1 class Lecture6 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 10 / Zheng-Liang Lu Java Programming 185 / 248

STUDENT LESSON A12 Iterations

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

SOFTWARE DEVELOPMENT 1. Control Structures 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

CS 61B Asymptotic Analysis Fall 2018

Algorithm efficiency can be measured in terms of: Time Space Other resources such as processors, network packets, etc.

Linked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list }

The Basic Parts of Java

Transcription:

Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue: the loop skips this iteration right after a continue statement is executed. In practice, jump statements in loops should be conditioned. Zheng-Liang Lu Java Programming 136 / 167

Example: Primality Write a program which determines if the input integer is a prime number. Let x > 1 be any natural number. Then x is said to be a prime number if x has no positive divisors other than 1 and itself. It is then straightforward to check if it is prime by dividing x by all natural numbers smaller than x. For speedup, you can divide x by only numbers smaller than x. (Why?) Zheng-Liang Lu Java Programming 137 / 167

1... 2 Scanner input = new Scanner(System.in); 3 System.out.println("Enter x > 2?"); 4 int x = input.nextint(); 5 boolean isprime = true; 6 input.close(); 7 8 for (int y = 2; y < Math.sqrt(x); y++) { 9 if (x % y == 0) { 10 isprime = false; 11 break; 12 } 13 } 14 15 if (isprime) { 16 System.out.println("Prime"); 17 } else { 18 System.out.println("Composite"); 19 } 20... Zheng-Liang Lu Java Programming 138 / 167

Exercise (Revisited) Redo the cashier problem by using an infinite loop with a break statement. 1... 2 while (true) { 3 System.out.println("Enter price ( 1 to exit):"); 4 curritem = input.nextint(); 5 if (curritem >= 0) { 6 amount += curritem; 7 } else if (curritem == 1) { 8 System.out.println("Total = " + amount); 9 break; 10 } 11 } 12... Zheng-Liang Lu Java Programming 139 / 167

Another Example Write a program which determines the holding years for an investment doubling its value. Let curr be the current amount, goal be the goal of this investment, and r be the annual interest rate. Then this investment should take at least n years so that the balance of the investment can double its value. Recall that the compounding formula is given by curr = curr (1 + r/100). Zheng-Liang Lu Java Programming 140 / 167

1... 2 int r = 18; // 18% 3 int curr = 100; 4 int goal = 200; 5 6 int years = 0; 7 while (curr <= goal) { 8 curr = (1 + r / 100.0); 9 years++; 10 } 11 12 System.out.println("Years = " + years); 13 System.out.println("Balance = " + curr); 14... Zheng-Liang Lu Java Programming 141 / 167

1... 2 int years = 0; // should be declared here; scope issue 3 for (; curr <= goal; years++) { 4 curr = (1 + r / 100); 5 } 6... 1... 2 int years = 1; // check this initial value 3 for (; true; years++) { 4 curr = (1 + r / 100); 5 if (curr >= goal) break; 6 } 7... A for loop can be an infinite loop by setting true or simply leaving empty in the condition statement. An infinite for loop with an if-break statement is equivalent to a normal while loop. Zheng-Liang Lu Java Programming 142 / 167

Equivalence: while and for Loops (Concluded) In general, a for loop may be used if the number of repetitions is known in advance. If not, a while loop is preferred. Zheng-Liang Lu Java Programming 143 / 167

Nested Loops A loop can be nested inside another loop. Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started anew. Zheng-Liang Lu Java Programming 144 / 167

Example Multiplication table Write a program which displays the multiplication table. Zheng-Liang Lu Java Programming 145 / 167

Formatting Console Output You can use System.out.printf () to display formatted output on the console. 1... 2 double amount = 1234.601; 3 double interestrate = 0.00528; 4 double interest = amount interestrate; 5 System.out.printf("Interest = %4.2f", interest); 6... Zheng-Liang Lu Java Programming 146 / 167

By default, a floating-point value is displayed with 6 digits after the decimal point. Zheng-Liang Lu Java Programming 147 / 167

Multiple Items to Print Items must match the format specifiers in order, in number, and in exact type. If an item requires more spaces than the specified width, the width is automatically increased. By default, the output is right justified. You may try the plus sign (+), the minus sign (-), and 0 in the middle of format specifiers. Say % + 8.2f, % 8.2f, and %08.2f. Zheng-Liang Lu Java Programming 148 / 167

1... 2 public static void main(string[] args) { 3 for (int i = 1; i <= 9; ++i) { 4 for (int j = 1; j <= 9; ++j) { 5 System.out.printf("%3d", i j); 6 } 7 System.out.println(); 8 } 9 } 10... Zheng-Liang Lu Java Programming 149 / 167

Exercise: Coupled Loops Zheng-Liang Lu Java Programming 150 / 167

1 public class PrintStarsDemo { 2 public static void main(string[] args) { 3 // case (a) 4 for (int i = 1; i <= 5; i++) { 5 for (int j = 1; j <= i; j++) { 6 System.out.printf(" "); 7 } 8 System.out.println(); 9 } 10 } 11 } Zheng-Liang Lu Java Programming 151 / 167

Analysis of Algorithms First, there may exist some algorithms for the same problem, which are supposed to be correct. Then we compare these algorithms. The first question is, Which one is more efficient? (Why?) We focus on the growth rate of the running time or space requirement as a function of the input size n, denoted by f (n). Zheng-Liang Lu Java Programming 152 / 167

O-notation 1 In math, O-notation describes the limiting behavior of a function when the argument tends towards a particular value or infinity, usually in terms of simpler functions. f (n) O(g(n)) as n if and only if there is a constant c > 0 and a real number n 0 such that f (n) c g(n) n n 0. (1) Note that O(g(n)) is a set featured by some simple function g(n). Hence f (n) O(g(n)) is equivalent to say that f (n) is one instance of O(g(n)). 1 See any textbook for data structures and algorithms. Zheng-Liang Lu Java Programming 153 / 167

For example, 8n 2 3n + 4 O(n 2 ) (tight bound). We say 8n 2 3n + 4 O(n 3 ) and 8n 2 3n + 4 / O(n). Zheng-Liang Lu Java Programming 154 / 167

Growth Rates for Fundamental Functions 2 2 See Table 4.1 and Figure 4.2 in Goodrich and etc, p. 161. Zheng-Liang Lu Java Programming 155 / 167

All in all, O-notation describes the asymptotic 3 upper bound of complexity of the algorithm. So O-notation is widely used to classify algorithms by how they respond to changes in input size. 4 Time complexity Space complexity 3 The asymptotic sense is that the input size n grows toward infinity. 4 Actually, there are Θ, θ, o, Ω, and ω which are used to classify algorithms. Zheng-Liang Lu Java Programming 156 / 167

References https://en.wikipedia.org/wiki/game_complexity https://en.wikipedia.org/wiki/p_versus_np_problem Zheng-Liang Lu Java Programming 157 / 167

1 class Lecture5 { 2 3 "Arrays" 4 5 } Zheng-Liang Lu Java Programming 158 / 167

Arrays An array stores a large collection of data which is of the same type. 1... 2 // assume the size variable exists above 3 T[] A = new T[size]; 4 // this creates an array of T type, referenced by A 5... T can be any data type. This statement comprises two parts: Declaring a reference Creating an array Zheng-Liang Lu Java Programming 159 / 167

Variable Declaration for Arrays In the left-hand side, it is a declaration for an array variable, which does not allocate real space for the array. In reality, this variable occupies only a certain space for the reference to an array. 5 If a reference variable does not refer to an array, the value of the variable is null. 6 In this case, you cannot assign elements to this array variable unless the array object has already been created. type. 5 Recall the stack and the heap in the memory layout. 6 Moreover, this holds for any reference variable. For example, the Scanner Zheng-Liang Lu Java Programming 160 / 167

Creating A Real Array All arrays of Java are objects. As seen before, the new operator returns the memory address of that object. Recall that the type of reference variables must be compatible to that of the array object. The variable size must be a positive integer for the number of elements. Note that the size of an array cannot be changed after the array is created. 7 7 You can try the ArrayList class. See any textbook for data structures. Zheng-Liang Lu Java Programming 161 / 167

Consider this array: 1 int[] A = new int[3]; Arrays in Memory The array is allocated contiguously in the memory. Note that all arrays are zero-based indexing. 8 (Why?) So we have A[0], A[1], and A[2]. 8 Same in C, C++, and more languages. Zheng-Liang Lu Java Programming 162 / 167

Array Initializer Arrays can be initialized when they are declared. When an array is created, all elements are assigned by default: 0 for all numeric primitive data types \u0000 for char type false for boolean type An array can also be initialized by enumerating all the elements. For example, 1 int[] A = {1, 2, 3}; Note that there is no need to use new if enumeration is used. Zheng-Liang Lu Java Programming 163 / 167

Processing Arrays When processing array elements, we often use a for loop. Since the size of the array is known, it is natural to use a for loop to manipulate the array. For all arrays, they have a field called length which records the size of this array. For example, use A.length to get the size of A. Zheng-Liang Lu Java Programming 164 / 167

Examples Initializing arrays with input values 1... 2 // let x be an integer array with a certain size 3 for (int i = 0; i < A.length; ++i) { 4 A[i] = input.nextint(); 5 } 6... Initializing arrays with random values 1... 2 for (int i = 0; i < A.length; ++i) { 3 A[i] = (int) (Math.random() 10); 4 } 5... Zheng-Liang Lu Java Programming 165 / 167

Displaying arrays 1... 2 for (int i = 0; i < A.length; ++i) { 3 System.out.printf("A[%d] = %d\n", i, A[i]); 4 } 5... Summing all elements 1... 2 int sum = 0; 3 for (int i = 0; i < A.length; ++i) { 4 sum += A[i]; 5 } 6... Zheng-Liang Lu Java Programming 166 / 167

Finding the extreme values 1... 2 int max = A[0]; 3 int min = A[0]; 4 for (int i = 1; i < A.length; ++i) { 5 if (max < A[i]) max = A[i]; 6 if (min > A[i]) min = A[i]; 7 } 8... How about the location of the extreme values? Zheng-Liang Lu Java Programming 167 / 167