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

Similar documents
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

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

1 class Lecture6 { 2 3 "Methods" // keywords: 8 return. Zheng-Liang Lu Java Programming 186 / 244

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

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

The return Statement

Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University

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

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

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

Example. Password generator

Example: Fibonacci Numbers

Scope of Variables. In general, it is not a good practice to define many global variables. 1. Use global to declare x as a global variable.

Example: Monte Carlo Simulation 1

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

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

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

Exercise (Revisited)

Object-Based Programming. Programming with Objects

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

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

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

switch-case Statements

CS115 Principles of Computer Science

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

Chapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

Arithmetic Compound Assignment Operators

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225

Lecture 5: Methods CS2301

Lecture #6-7 Methods

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

Methods and Functions

Pace University. Fundamental Concepts of CS121 1

Java Classes: Math, Integer A C S L E C T U R E 8

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

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

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

COMP 202 Java in one week

STUDENT LESSON A12 Iterations

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

1001ICT Introduction To Programming Lecture Notes

Methods: A Deeper Look

Chapter 6 Recursion. The Concept of Recursion


Example Program. public class ComputeArea {

Global Variables. ˆ Unlike local variables, global variables are available to all functions involved.

Functions. Systems Programming Concepts

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

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO?

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

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

AP CS Unit 3: Control Structures Notes

Loops (while and for)

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Chapter 6: Methods. Objectives 9/21/18. Opening Problem. Problem. Problem. Solution. CS1: Java Programming Colorado State University

4. Java language basics: Function. Minhaeng Lee

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

Programming Exercise 7: Static Methods

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.

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

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

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

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

Zheng-Liang Lu Java Programming 45 / 79

Decision-Making and Repetition

Chapter 3. Selections

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

Values in 2 s Complement

Midterm Examination (MTA)

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

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

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

C22a: Problem Solving using Recursion

C Functions. 5.2 Program Modules in C

Arithmetic Compound Assignment Operators

Mandatory Assignment 1, INF 4130, 2017

Recursion. Fundamentals of Computer Science

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

CS141 Programming Assignment #6

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

Introduction to Computer Science Unit 2. Notes

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Course Outline. Introduction to java

A function that invokes itself is said to

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

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

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

There are three questions on this exam. You have 2 hours to complete it. Please indent your program so that it is easy for the grader to read.

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

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

Top-Down Program Development

Ch. 6. User-Defined Methods

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Computer Science & Engineering 150A Problem Solving Using Computers

Transcription:

Exercise Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram. Zheng-Liang Lu Java Programming 197 / 227

1... 2 int[] hist = new int[5]; 3 // hist[0]: the counter for 90 100 4 // hist[1]: the counter for 80 89 5 //... 6 // hist[4]: the counter for 0 59 7 8 Scanner in = new Scanner(System.in); 9 int inputvalue; 10 do { 11 do { 12 System.out.println("Enter x? ( 1 to exit)"); 13 inputvalue = in.nextint(); 14 } while (inputvalue!= 1 && (inputvalue < 0 inputvalue > 100)); 15 if (inputvalue >= 90) ++hist[0]; 16 else if (inputvalue >= 80) ++hist[1]; 17 else if (inputvalue >= 70) ++hist[2]; 18 else if (inputvalue >= 60) ++hist[3]; 19 else if (inputvalue >= 0) ++hist[4]; 20 else System.out.println("End of input."); 21 } while (inputvalue!= 1); 22 in.close(); 23 Zheng-Liang Lu Java Programming 198 / 227

24 int total = 0; 25 for (int i = 0; i < hist.length; i++) { 26 total += hist[i]; 27 } 28 System.out.printf("Total: %d\n", total); 29 30 int[] tick = {0, 60, 70, 80, 90, 101}; 31 for (int i = 0; i < 5; i++) { 32 System.out.printf("%3d %3d: ", tick[i], tick[i + 1] 1); 33 for (int j = 0; j < hist[i]; j++) { 34 System.out.printf(" "); 35 } 36 System.out.printf("\n"); 37 } 38... Shall we rearrange the codes in order to reduce the complexity of the main method? Zheng-Liang Lu Java Programming 199 / 227

1... 2 static int[] inputmethod() { 3 int[] record = new int[5]; 4 Scanner in = new Scanner(System.in); 5 int inputvalue; 6 do { 7 do { 8 System.out.println("Enter x? ( 1 to exit)"); 9 inputvalue = in.nextint(); 10 } while (inputvalue!= 1 && (inputvalue < 0 inputvalue > 100)); 11 if (inputvalue >= 90) ++record[0]; 12 else if (inputvalue >= 80) ++record[1]; 13 else if (inputvalue >= 70) ++record[2]; 14 else if (inputvalue >= 60) ++record[3]; 15 else if (inputvalue >= 0) ++record[4]; 16 else System.out.println("End of input."); 17 } while (inputvalue!= 1); 18 in.close(); 19 return record; 20 } 21 22 23 Zheng-Liang Lu Java Programming 200 / 227

24 static void displayhistogram(int[] record) { 25 int total = 0; 26 for (int i = 0; i < cnt.length; i++) { 27 total += cnt[i]; 28 } 29 System.out.printf("Total: %d\n", total); 30 31 int[] tick = {0, 60, 70, 80, 90, 101}; 32 for (int i = 0; i < 5; i++) { 33 System.out.printf("%3d %3d: ", tick[i], tick[i + 1] 1); 34 for (int j = 0; j < record[i]; j++) { 35 System.out.printf(" "); 36 } 37 System.out.printf("\n"); 38 } 39 } 40... Zheng-Liang Lu Java Programming 201 / 227

1... 2 public static void main(string[] args) { 3 int[] hist = inputmethod(); 4 displayhistogram(hist); 5 } 6... In practice, we make the main method as simple as possible. Zheng-Liang Lu Java Programming 202 / 227

Math Class The Math class contains the methods needed to perform basic mathematical functions. The Math class is public. All methods of Math class are public and static with two global constants Math.PI 1 and Math.E 2. The Math class provides common methods like: max, min, round, ceil, floor, abs, pow, exp, sqrt, cbrt, log, log10, sin, cos, asin, acos, and random. Full document of Math class can be found here. You are expected be able to read the document! 1 π is a mathematical constant, the ratio of a circle s circumference to its diameter, commonly approximated as 3.141593. 2 e is the base of the natural logarithm. It is approximately equal to 2.71828. Zheng-Liang Lu Java Programming 203 / 227

Example Password generator Write a program which generates ten characters as a password. There may be lower-case letters, upper-case letters, and digital characters in the character sequence. Recall that a character is encoded using an integer. How to generate these characters randomly? Zheng-Liang Lu Java Programming 204 / 227

1... 2 static char getrandomuppercaseletter() { 3 return (char)(math.random() ( Z A + 1) + A ); 4 } 5 6 static char getrandomlowercaseletter() { 7 return (char)(math.random() ( z a + 1) + a ); 8 } 9 10 static char getrandomdigitalcharacter() { 11 return (char)(math.random() ( 9 0 + 1) + 0 ); 12 } 13... Zheng-Liang Lu Java Programming 205 / 227

1... 2 public static void main (String[] args) { 3 for (int i = 1; i <= 10; ++i){ 4 int type = (int) (Math.random() 3); 5 switch (type) { 6 case 0: 7 System.out.printf("%c", getrandomuppercaseletter()); 8 break; 9 case 1: 10 System.out.printf("%c", getrandomlowercaseletter()); 11 break; 12 case 2: 13 System.out.printf("%c", getrandomdigitalcharacter()); 14 break; 15 } 16 } 17 } 18... Zheng-Liang Lu Java Programming 206 / 227

Method Overloading Overloading methods enables you to define the methods with the same name as long as their signatures are different. Overloading methods can make programs clearer and more readable. Name conflict is ok. Make sure the signatures differ; the overloaded methods have different parameter lists. Note that you cannot overload methods merely based on different modifiers or return types. Zheng-Liang Lu Java Programming 207 / 227

Example (Revisit) Printing stars Write a program which prints a certain number of lines with some symbol determined by the user. The program repeats itself until the input number is negative. In addition, use * as the default symbol if the input is left blank. Zheng-Liang Lu Java Programming 208 / 227

1... 2 static void print(int n) { 3 for (int i = 1; i <= n; i++) { 4 for (int j = 1; j <= i; j++) { 5 System.out.printf(" "); 6 } 7 System.out.println(); 8 } 9 } 10 11 static void print(int n, String m) { 12 for (int i = 1; i <= n; i++) { 13 for (int j = 1; j <= i; j++) { 14 System.out.printf(m); 15 } 16 System.out.println(); 17 } 18 } 19... Zheng-Liang Lu Java Programming 209 / 227

1... 2 while (true) { 3 System.out.println("Enter n =? "); 4 n = Integer.parseInt(input.nextLine()); 5 if (n > 0) { 6 System.out.println("Enter a symbol? "); 7 m = input.nextline(); 8 if (m.equals("")) print(n); 9 else print(n, m); 10 } else { 11 System.out.println("Bye."); 12 break; 13 } 14 } 15... The method Integer.parseInt() converts the input string to an integer. The method nextline() returns a string from the keyboard. The method equals() is a String method used to compare if the two strings are identical. Zheng-Liang Lu Java Programming 210 / 227

Divide and Conquer When developing a program, you can use the divide-andconquer strategy, aka stepwise refinement, to decompose the original problem into subproblems. The subproblems can be further decomposed into smaller, more manageable problems. Pros: easier to write, reuse, debug, test, modify, maintain, and better facilitating teamwork For most problems, do not write the entire program at once. 3 3 So you need more skills such that system analysis, project management, and software engineering. Zheng-Liang Lu Java Programming 211 / 227

Recursion 4 Recursion is the process of defining something in terms of itself. A method that calls itself is said to be recursive. Recursion is an alternative form of program control. It is essentially repetition without a loop. 4 Recursion is a commom pattern in nature. Zheng-Liang Lu Java Programming 212 / 227

Try Fractal. Zheng-Liang Lu Java Programming 213 / 227

Example The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than and equal to n. Note that 0! = 1. For example, 5! = 5 4 3 2 1 = 5 4! = 120. Can you find the pattern? n! = n (n 1)! In general, f (n) = n f (n 1). Zheng-Liang Lu Java Programming 214 / 227

Write a program which determines n!. 1... 2 static int factorial(int n) { 3 if (n > 0) { 4 return n factorial(n 1); 5 } else { 6 return 1; // base case 7 } 8 } 9... Note that there must be a base case in recursion. Time complexity: O(n) Can you implement the same method by using a loop? Zheng-Liang Lu Java Programming 215 / 227

Zheng-Liang Lu Java Programming 216 / 227

Equivalence: Loop Version 1... 2 int y = 1; 3 for (int i = 1; i < = 10; i++) { 4 y = i; 5 } 6... Time complexity: O(n) One intriguing question is, Can we always turn a recursive method into the loop version of that? Yes, theoretically. 5 5 The Church-Turing Thesis proves it if the memory serves. Zheng-Liang Lu Java Programming 217 / 227

Remarks Recursion bears substantial overhead. So the recursive algorithm may execute a bit more slowly than the iterative equivalent. Additionally, a deeply recursive method depletes the call stack, which is limited, and causes stack overflow soon. Zheng-Liang Lu Java Programming 218 / 227

Exercise Fibonacci numbers Write a program which determines F n, the (n + 1)-th Fibonacci number. The first 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. The sequence of Fibonacci numbers can be defined by the recurrence relation F n = F n 1 + F n 2, where F 0 = 0, F 1 = 1, and n 2. Zheng-Liang Lu Java Programming 219 / 227

Zheng-Liang Lu Java Programming 220 / 227

1... 2 static int fibrecursive(int n) { 3 if (n == 0) return 0; 4 else if (n == 1) return 1; 5 else return fibrecursive(n 1) + fibrecursive(n 2); 6 } 7... This recursive implementation is straightforward. Yet, this algorithm isn t efficient since it requires more time and memory. Time complexity: O(2 n ) (Why?!) Zheng-Liang Lu Java Programming 221 / 227

You can try an iterative approach for Fibonacci numbers. 1... 2 static double fibiter(int n) { 3 int x = 0, y = 1; 4 if (n < 2) { 5 return (n == 1)? y : x; 6 } else { 7 for (int i = 0; i < n; ++i){ 8 int tmp = x + y; 9 x = y; 10 y = tmp; 11 } 12 return y; 13 } 14 } 15... So it can be done in O(n) time. Can you find a linear recursion for Fibonacci numbers? Zheng-Liang Lu Java Programming 222 / 227

Computational Thinking 6 To think about computing, we need to be attuned to three fields: science, technology, and society. Computational thinking shares with mathematical thinking: the way to solve problems engineering thinking: the way to design and evaluating a large, complex system scientific thinking: the way to understand computability, intelligence, the mind and human behavior. 6 You should read this: http://rsta.royalsocietypublishing.org/content/366/1881/3717.full Zheng-Liang Lu Java Programming 223 / 227

Computational Thinking Is Everywhere! The essence of computational thinking is abstraction. An algorithm is an abstraction of a step-by-step procedure for taking input and producing some desired output. A programming language is an abstraction of a set of strings each of which when interpreted effects some computation. And more. The abstraction process, which is to decide what details we need to highlight and what details we can ignore, underlies computational thinking. The abstraction process also introduces layers. Well-defined interfaces between layers enable us to build large, complex systems. Zheng-Liang Lu Java Programming 224 / 227

Example: Abstraction of Computer System Zheng-Liang Lu Java Programming 225 / 227

Example: Methods as Control Abstraction Zheng-Liang Lu Java Programming 226 / 227

Abstraction (Concluded) Control abstraction is the abstraction of actions while data abstraction is that of data structures. One can view the notion of an object as a way to combine abstractions of data and code. Zheng-Liang Lu Java Programming 227 / 227