CS1150 Principles of Computer Science Loops (Part II)

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

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

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

Chapter 4 Loops. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

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

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

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

Loops. CSE 114, Computer Science 1 Stony Brook University

CS1150 Principles of Computer Science Arrays

3chapter C ONTROL S TATEMENTS. Objectives

Iteration statements - Loops

Lecture 1 Java SE Programming

CONDITIONAL EXECUTION

CS1150 Principles of Computer Science Methods

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

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

CS1150 Principles of Computer Science Methods

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

CS1150 Principles of Computer Science Loops

Motivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

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

Chapter 1: Introduction to Computers, Programs, and Java

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

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.

Example: Monte Carlo Simulation 1

Repetition with for loops

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

CS110D: PROGRAMMING LANGUAGE I

CS1150 Principles of Computer Science Arrays

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

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

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

CP122 CS I. Iteration

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

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

Repetition, Looping. While Loop

Introduction to the Java Basics: Control Flow Statements

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

Recap: Assignment as an Operator CS 112 Introduction to Programming

Repetition Structures

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Chapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type

Flow Control. CSC215 Lecture

CS 112 Introduction to Programming

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

The for Loop. Lesson 11

Lecture 5: Methods CS2301

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

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

Repetition, Looping CS101

Object Oriented Software Design

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

Activity 6: Loops. Content Learning Objectives. Process Skill Goals

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

Assignment 2.4: Loops

AP CS Unit 3: Control Structures Notes

1.3 Conditionals and Loops

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

ECE 122. Engineering Problem Solving with Java

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

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

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

Java Bytecode (binary file)

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Expressions & Flow Control

Chapter 3 Selection Statements

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

( &% class MyClass { }

Controls Structure for Repetition

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

Building Java Programs Chapter 2

Conditionals, Loops, and Style

Scope of this lecture. Repetition For loops While loops

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

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

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

Some Sample AP Computer Science A Questions - Solutions

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

Chapter 17. Iteration The while Statement

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

Accelerating Information Technology Innovation

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Chapter 5: Loops and Files

Methods and Functions

CS 106 Introduction to Computer Science I

Looping. Arizona State University 1

Condi(onals and Loops

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.

Transcription:

CS1150 Principles of Computer Science Loops (Part II) Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs

Review Is this an infinite loop? Why (not)? int count = 1; while (count <= 5); { System.out.println("The value of count is " + count); count++; CS4500/5500 UC. Colorado Springs

Review Is this an infinite loop? Why (not)? int count = 1; while (count <= 5); { System.out.println("The value of count is " + count); count++; int count = 1; do { count++; System.out.println( Count = " + count); while (count<= 5); CS4500/5500 UC. Colorado Springs

Overview While loop Do while loop For loop CS1150 UC. Colorado Springs

For loops For loops are used to execute a loop a preset number of times for ( 1 initial-action; 2 loop-condition; 4 action-after-each-iteration) { 3 Statement(s); 1. The control variable is initialized to a start value 2. The control variable is compared to the loop condition 3. If the condition is true, then loop body is executed 4. The control variable is updated after loop body completes 5. Steps 2-4 are repeated as long as the loop condition is true CS4500/5500 UC. Colorado Springs

for Loops for (initial-action; loop-continuationcondition; action-after-each-iteration){ // loop body; Statement(s); int i; for (i = 0; i < 100; i++) { System.out.println( "Welcome to Java!"); 6

Rules of for loops The control structure of for-loop must be in parentheses o for (i=0; i<= 2; i++) { statements; The loop condition (i <= 2) must be a boolean expression The control variable (i): not recommended to be changed within the for-loop body Curly braces not necessary if only one statement in loop o Best practice is to always include curly braces CS4500/5500 UC. Colorado Springs

Trace for Loop int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); Declare i 8

Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); Execute initializer i is now 0 9

Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); (i < 2) is true since i is 0 10

Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); Print Welcome to Java 11

Trace for Loop, cont. Execute adjustment statement int i; i now is 1 for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); 12

Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); (i < 2) is still true since i is 1 13

Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); Print Welcome to Java 14

Trace for Loop, cont. Execute adjustment statement int i; i now is 2 for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); 15

Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); (i < 2) is false since i is 2 16

Trace for Loop, cont. Exit the loop. Execute the next int i; statement after the loop for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); Let s look at ForPrintNTimes.java. 17

Note You may declare the control variable outside/within the for-loop for (int j = 0; j <= 5; j++) { System.out.println ("For loop iteration = " + j); int j; for (j = 0; j <= 5; j++) { System.out.println ("For loop iteration = " + j); Note on variable scope (the area a variable can be referenced) o o Declaring control variable before the for loop cause its scope to be inside and outside for-loop Declaring the control variable in the for-loop causes its scope to be only inside the for loop If I tried to use the variable j outside the for-loop - error CS4500/5500 UC. Colorado Springs

Note The initial-action in a for loop can be a list of zero or more comma-separated expressions. The action-after-eachiteration in a for loop can be a list of zero or more commaseparated statements. Therefore, the following is correct, but rarely used in practice. for (int i = 0, j = 0; (i + j < 10); i++, j++) { // Do something 19

Note If the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus the statement given below in (a), which is an infinite loop, is correct. Nevertheless, it is better to use the equivalent loop in (b) to avoid confusion: for ( ; ; ) { // Do something (a) Equivalent while (true) { // Do something (b) Eclipse only allowed this to happen if there are no statements following the for- loop If statements followed the loop, Eclipse places an error "unreachable code" on the statement following the loop 20

Caution Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below: for (int i=0; i<10; i++); { Logic Error System.out.println("i is " + i); 21

Caution, cont. Similarly, the following loop is also wrong: int i=0; Logic Error while (i < 10); { System.out.println("i is " + i); i++; In the case of the do loop, the following semicolon is needed to end the loop. int i=0; do { System.out.println("i is " + i); i++; while (i<10); Correct 22

Which Loop to Use? The three forms of loop statements, while, do-while, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. For example, a while loop in (a) in the following figure can always be converted into the following for loop in (b): while (loop-continuation-condition) { // Loop body (a) Equivalent for ( ; loop-continuation-condition; ) // Loop body (b) A for loop in (a) in the following figure can generally be converted into the following while loop in (b): for (initial-action; loop-continuation-condition; action-after-each-iteration) { // Loop body; (a) Equivalent 23 initial-action; while (loop-continuation-condition) { // Loop body; action-after-each-iteration; (b)

Recommendations Use the one that is most intuitive and comfortable. In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition. 24 Fahrenheit2CelsiusForLoop.java

RandomNumbers example Math.random() o Returns a double value, greater than or equal to 0.0 and less than 1.0, i.e., [0.0, 1.0) double randomdouble; randomdouble = Math.random(); // [0.0, 1.0) o How to generate a random double in [0.0, 10.0)? randomdouble = Math.random() * 10; o How to generate a random integer in [0, 10)? int randomint; randomint = (int) (Math.random() * 10); Note: DO NOT use (int)math.random()*10 CS4500/5500 UC. Colorado Springs

RandomNumbers example Math.random() o o How to generate a random integer between [lower, upper)? Example: int lower=100, upper=120; randomdouble = Math.random(); // [0.0, 1.0) randomdouble = randomdouble * (upper-lower); // expand: [0.0, 20.0) randomdouble = lower + randomdouble; // shift: [100.0, 120.0) randomint = (int) randomdouble; // cast: double à int Or in one step randomint = (int) (lower + Math.random() * (upper-lower)); Let s look at RandomNumbers.java and AdditionQuiz.java CS4500/5500 UC. Colorado Springs

Nested Loops If statements can be nested If (boolean expression) { if(boolean expression) { statement(s); // end of inner if // end of outer if Loops can be nested too CS4500/5500 UC. Colorado Springs

Nested Loops For loop within a for loop for (int outer = 1; outer < 3; outer++) { System.out.println ("The outer loop iteration is = " + outer); // This is the inner for loop // It will do all iterations before outer loop does another iteration for (int inner = 1; inner <= 5; inner++) { System.out.println (" The inner loop iteration is = " + inner); CS4500/5500 UC. Colorado Springs

Nested Loops While loop within a while loop int outer = 1; while (outer < 3) { System.out.println ("The outer loop iteration is = " + outer); //inner loop: It will do all iterations before outer loop does another iteration int inner = 1; while (inner <= 5) { System.out.println (" The inner loop iteration is = " + inner); inner++; outer++; CS4500/5500 UC. Colorado Springs

Nested Loops Problem: Write a program that uses nested for loops to print a multiplication table. MultiplicationTable.java 30

Using break and continue Break in loops o o o Used "break" in switch statements to end a case Can be used in a loop to terminate a loop Breaks out of loop Continue in loops o o Used to end current iteration of loop Program control goes to end of loop body CS4500/5500 UC. Colorado Springs

break public class TestBreak { public static void main(string[] args) { int sum = 0; int number = 0; while (number < 20) { number++; sum += number; if (sum >= 100) break; System.out.println("The number is " + number); System.out.println("The sum is " + sum); 32

continue public class TestContinue { public static void main(string[] args) { int sum = 0; int number = 0; while (number < 20) { number++; if (number == 10 number == 11) continue; sum += number; System.out.println("The sum is " + sum); 33

Guessing Number Problem Revisited Let s look at AdditionQuiz (random number + break example) 34

Using break and continue There are cases when the use of a break or continue in a loop is necessary Overusing or improper use can make program hard to read, maintain, and debug. Best practice is to never use these unless you have a specific situation CS4500/5500 UC. Colorado Springs

Practice! Predicting tuition The tuition for a university is currently $10,000. It will increase by 7% each year In how many years will the tuition be doubled? o o o Which loop to use? Statement(s) to be repeated? Condition to check? CS4500/5500 UC. Colorado Springs

Summary While loop Do while loop For loop Breack and continue CS1150 UC. Colorado Springs