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

Similar documents
Example: Monte Carlo Simulation 1

switch-case Statements

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.

Arithmetic Compound Assignment Operators

Exercise (Revisited)

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

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

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

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

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

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

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

Arithmetic Compound Assignment Operators

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

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

Values in 2 s Complement

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

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

Loops. CSE 114, Computer Science 1 Stony Brook University

IEEE Floating-Point Representation 1

Repetition, Looping. While Loop

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

Computer Programming I - Unit 5 Lecture page 1 of 14

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

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

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

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

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

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

CompSci 125 Lecture 11

Iteration statements - Loops

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

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

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

Date: Dr. Essam Halim

Midterm Examination (MTA)

Loops and Expression Types

REPETITION CONTROL STRUCTURE LOGO

AP Programming - Chapter 6 Lecture

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

CS1150 Principles of Computer Science Loops (Part II)

Lecture 7 Tao Wang 1

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

Java Coding 3. Over & over again!

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

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

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

STUDENT LESSON A12 Iterations

Chapter 4: Control structures. Repetition

Introduction to Java & Fundamental Data Types

Controls Structure for Repetition

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

Loops (while and for)

Chapter 4: Control structures

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

Repetition Structures

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

Control Statements: Part 1

1 Short Answer (10 Points Each)

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

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

ECE 122. Engineering Problem Solving with Java

Problem Solving With Loops

Assignment 2.4: Loops

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

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

C++ Quick Reference. switch Statements

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

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

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

Loops / Repetition Statements

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Loops. Repeat after me

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

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

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

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

Chapter 4 Introduction to Control Statements

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

Repetition with for loops

AP CS Unit 3: Control Structures Notes

COMP-202 Unit 4: Programming with Iterations

CS112 Lecture: Loops

Flow of Control: Loops. Chapter 4

CS141 Programming Assignment #6

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

Expression statements are formed by adding a semicolon to the end of certain types of expressions.

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

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

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

CS112 Lecture: Repetition Statements

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

Some Sample AP Computer Science A Questions - Solutions

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

Problem Solving and 'C' Programming

Write a program which converts all lowercase letter in a sentence to uppercase.

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

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

Transcription:

Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random() 10); 4 int y = (int) (Math.random() 10); 5 int ans = x + y; 6 7 System.out.println(x + " + " + y + " =? "); 8 int z = input.nextint(); 9 10 while (z!= ans) { 11 System.out.println("Try again? "); 12 z = input.nextint(); 13 } 14 System.out.println("Correct."); 15 input.close(); 16... Zheng-Liang Lu Java Programming 116 / 145

Loop Design Strategy Writing a correct loop is not an easy task for novice programmers. Consider 3 steps when writing a loop: Find the pattern: identify the statements that need to be repeated. Wrap: put these statements in a loop. Set the continuation condition: translate the criteria from the real world problem into computational conditions. 1 1 Not unique. Zheng-Liang Lu Java Programming 117 / 145

Sentinel-Controlled Loop Another common technique for controlling a loop is to designate a special value when reading and processing a set of values. This special input value, known as a sentinel value, signifies the end of the loop. For example, the operating systems and the GUI apps. Zheng-Liang Lu Java Programming 118 / 145

Example: Cashier Problem Write a program which sums positive integers from the input except for -1 to exit, and displays the sum. 1... 2 Scanner in = new Scanner(System.in); 3 int sum = 0; 4 System.out.println("Enter a positive integer ( 1 to exit ): "); 5 int x = in.nextint(); 6 while (x!= 1) { 7 if (x > 0) sum += x; 8 System.out.println("Enter a positive integer ( 1 to exit): "); 9 x = in.nextint(); 10 } 11 System.out.println("sum = " + sum); 12 in.close(); 13... Line 8 and 9 are the recurrence of Line 4 and 5?! Zheng-Liang Lu Java Programming 119 / 145

do-while Loops A do-while loop is the same as a while loop except that it does execute the loop body first and then checks the loop continuation condition. 1... 2 do { 3 // loop body 4 } while (condition); // Do not miss the semicolon! 5... Note that there is a semicolon at the end the do-while loop. The do-while loops are also called posttest loop, in contrast to while loops, which are pretest loops. Zheng-Liang Lu Java Programming 120 / 145

Zheng-Liang Lu Java Programming 121 / 145

Example (Revisted) Write a program which sums positive integers from the input except for -1 to exit, and displays the sum. 1... 2 Scanner in = new Scanner(System.in); 3 int sum = 0; 4 int x = 0; 5 6 do { 7 System.out.println("Enter a positive integer ( 1 to exit): "); 8 x = in.nextint(); 9 if (x >= 0) sum += x; 10 } while (x!= 1); 11 System.out.println("Sum = " + sum); 12 in.close(); 13... Zheng-Liang Lu Java Programming 122 / 145

Exercise Write a program which allows the user to enter positive integers except for -1 to exit, and displays the maximum. Zheng-Liang Lu Java Programming 123 / 145

1... 2 Scanner in = new Scanner(System.in); 3 int max = 0, x; 4 do{ 5 System.out.println("Enter a positive integer ( 1 to exit): "); 6 x = in.nextint(); 7 if(max < x) { 8 max = x; 9 } 10 System.out.println("Max = " + max); 11 } while (x!= 1); 12 in.close(); 13... Zheng-Liang Lu Java Programming 124 / 145

for Loops A for loop generally uses a variable to control how many times the loop body is executed and when the loop terminates. 1... 2 for(init; condition; increment) { 3 // loop body 4 } 5... init: declare and initialize a variable condition: a continuation criterion increment: how the variable changes after each iteration Note that the three terms are separated by semicolons. Zheng-Liang Lu Java Programming 125 / 145

Sum from 1 to 100 Example Write a program which sums from 1 to 100. 1... 2 int sum = 0; 3 for (int i = 1; i <= 100; ++i) 4 sum = sum + i; 5... Compared to the while version, 1... 2 int sum = 0; 3 int i = 1; 4 while (i <= 100) { 5 sum = sum + i; 6 ++i; 7 } 8... Zheng-Liang Lu Java Programming 126 / 145

Zheng-Liang Lu Java Programming 127 / 145

Example: Selection Resided in Loop Display all even numbers Write a program which displays all even numbers smaller than 100. An even number is an integer of the form x = 2k, where k is an integer. Zheng-Liang Lu Java Programming 128 / 145

You may use modular operator (%). 1... 2 for (int i = 1; i <= 100; i++) { 3 if (i % 2 == 0) 4 System.out.println(i); 5 } 6... You may consider this alternative: 1... 2 for (int i = 2; i <= 100; i += 2) { 3 System.out.println(i); 4 } 5... How about odd numbers? Zheng-Liang Lu Java Programming 129 / 145

Jump Statements The keywords, break and continue, are often used in loop 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 are placed within selection structures in loops. (Why?) Zheng-Liang Lu Java Programming 130 / 145

Example isprime problem Write a program which determines if the input integer is a prime number. Recall that a prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Let x be any natural number. The most naive approach is to divide x by all natural numbers smaller than x. A better approach is to divide x by all natural numbers smaller than x. (Why?) Zheng-Liang Lu Java Programming 131 / 145

1... 2 Scanner input = new Scanner(System.in); 3 System.out.println("Please enter an integer: "); 4 int x = input.nextint(); 5 boolean isprime = true; 6 in.close(); 7 8 for (int i = 2; i <= Math.sqrt(x); i++) { 9 if ((x % i) == 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 132 / 145

Exercise (Revisited) Redo the cashier problem by using an infinite loop with a jump statement. 1... 2 while (true) { 3 System.out.println("Enter a positive integer ( 1 to exit): "); 4 x = input.nextint(); 5 if (x >= 0) { 6 sum += x; 7 } else if (x == 1) { 8 System.out.println("Sum = " + sum); 9 break; 10 } else { 11 System.out.println("Try again."); 12 } 13 } 14 in.close(); 15... Zheng-Liang Lu Java Programming 133 / 145

Equivalence: while and for Loops Compounding problem Consider that one saves 10, 000 NTD in a bank. Write a program which determines the number of years n such that the compounding amount of saving exceeds 15, 000 NTD as r is specified. We may need the following variables: principal: the starting amount curramount: the current balance of saving goalamount: the amount we set r: interest rate, herein, assuming constant Recall that the compounding formula. Stopping criterion? Continuation criterion? Zheng-Liang Lu Java Programming 134 / 145

1... 2 public static void main(string[] args) { 3 Scanner inpunt = new Scanner(System.in); 4 5 System.out.println("Interest rate (%) =?"); 6 double r = input.nextdouble(); 7 System.out.println("Principal =?"); 8 int principal = input.nextint(); 9 System.out.println("Goal =?"); 10 int goalamount = input.nextint(); 11 int curramount = principal; 12 in.close(); 13 14 int years = 0; 15 while (curramount < goalamount) { // continuation criterion 16 curramount = (1 + r / 100); 17 years++; 18 } 19 20 System.out.println("Years = " + years); 21 System.out.println("Amount = " + amount); 22 } 23... Zheng-Liang Lu Java Programming 135 / 145

1... 2 int years; // should be declared; scope issue 3 for (years = 1; true; n++) { 4 curramount = (1 + r / 100); 5 if (curramount >= goalamount) // stopping criterion 6 break; 7 } 8... A for loop can be an infinite loop by setting true or simply leaving empty in the condition in for. An infinite for loop with a break statement is equivalent to a normal while loop. Zheng-Liang Lu Java Programming 136 / 145

Equivalence: while and for Loops (Concluded) You can use a for loop, a while loop, or a do-while loop, whichever is convenient. 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 137 / 145

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 138 / 145

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

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 140 / 145

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

Example: Multiple Items 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 142 / 145

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 System.out.println(); 7 } 8 } 9... Zheng-Liang Lu Java Programming 143 / 145

Exercise: Coupled Loops Zheng-Liang Lu Java Programming 144 / 145

1 public class printstars { 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 145 / 145