Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Similar documents
Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal

Control Statements Review CSC 123 Fall 2018 Howard Rosenthal

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

Repetition, Looping. While Loop

Chapter 4: Control structures. Repetition

Repetition and Loop Statements Chapter 5

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

Chapter 4: Control structures

Introduction to the Java Basics: Control Flow Statements

STUDENT LESSON A12 Iterations

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

Introduction. C provides two styles of flow control:

Controls Structure for Repetition

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

Repetition, Looping CS101

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

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

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

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

Top-Down Program Development

Recap: Assignment as an Operator CS 112 Introduction to Programming

Computer Programming I - Unit 5 Lecture page 1 of 14

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

Loops. CSE 114, Computer Science 1 Stony Brook University

CS 112 Introduction to Programming

Flow of Control: Loops. Chapter 4

Repetition Structures

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

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

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

REPETITION CONTROL STRUCTURE LOGO

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

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

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

Iteration statements - Loops

LECTURE 5 Control Structures Part 2

CS 106 Introduction to Computer Science I

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

Chapter 3. Selections

204111: Computer and Programming

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

Java Coding 3. Over & over again!

Looping. Arizona State University 1

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Repetition with for loops

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

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

CS 106 Introduction to Computer Science I

Chapter 5: Loops and Files

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

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

Chapter Goals. Contents LOOPS

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

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

CS1150 Principles of Computer Science Loops (Part II)

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

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

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

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

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

CS110D: PROGRAMMING LANGUAGE I

CS112 Lecture: Repetition Statements

Lesson 6A Loops. By John B. Owen All rights reserved 2011, revised 2014

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

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

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

Principles of Computer Science I

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

Flow Control. CSC215 Lecture

Methods CSC 121 Fall 2016 Howard Rosenthal

3chapter C ONTROL S TATEMENTS. Objectives

CS121: Computer Programming I

This Week s Agenda (Part A) CS121: Computer Programming I. Changing Between Loops. Things to do in-between Classes. Answer. Combining Statements

Chapter 17. Iteration The while Statement

The for Loop. Lesson 11

St. Edmund Preparatory High School Brooklyn, NY

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

Bjarne Stroustrup. creator of C++

3 The L oop Control Structure

Computer Science is...

Loops and Files. of do-while loop

Introduction to Java & Fundamental Data Types

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

Full file at

Last Class. While loops Infinite loops Loop counters Iterations

CS112 Lecture: Loops

AP Programming - Chapter 6 Lecture

Warmup : Name that tune!

Loops. GEEN163 Introduction to Computer Programming

Loops / Repetition Statements

Module 4: Decision-making and forming loops

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

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

Iterative Languages. Scoping

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

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

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Transcription:

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while for Learn nested looping Learn how to use break statements to exit a loop Begin to learn how to deal with situations where faulty or out of range input is supplied 2

Introduc$on to Loops Many of the tasks performed by computers require repetition, often massive repetition Using repetitive syntax can make your code more concise and easier to write and debug Java has three types of repetitive constructs (also known as loops): while; dowhile; or for Loops are built out of several fundamental statements because there are three things (in each of the three types of loops) that must be done correctly: The loop must be initialized correctly. The ending condition must be tested correctly. The body of the loop must change the condition that is tested. Overlooking one of these aspects results in a defective loop and a sometimes difficult to find program bug! Usually each of these three considerations is located in a different spot. No wonder that loops often go wrong! You have to plan out the logic of your program in order to effectively use loops and conditionals 3

Types of Loops type counting loop sentinel-controlled loop result-controlled loop description Uses a loop control variable to count upwards or downwards (usually by an integer increment.) Loop keeps going until a special value is encountered in the data. Loop keeps going until a test determines that the desired result has been achieved. 4

The while Statement Here is a program with a loop. It contains a while statement, followed by a block of code. A block is a group of statements enclosed in braces. // Example of a while loop public class LoopExample public static void main (String[] args ) // start count out at one int count = 1; while ( count <= 3 ) System.out.println( "count is:" + count ); count = count + 1; // add one to count System.out.println( "Done with the loop" ); 5

The Basic Syntax of the while Statement while (condition) statement 1; statement 2; o 0 o statement n; You execute through the entire block repetitively until the condition is false unless you encounter a break statement The break will typically occur based on a separate condition tested with an if statement 6

Basic Terminology of the while Statement The condition is a Boolean expression: something that evaluates to true or false. The condition can be complicated, using many relational operators and logical operators. A single statement is allowed Without braces only one statement is executed inside the loop The block or single executable statement is sometimes called the loop body. If one of the statements in the while block doesn t eventually change the value of the condition then the loop goes on forever. The while loop may not be executed at all if the initial condition is false There is not a semi-colon after the while statement. If you put one there you will end the loop before it executes anything 7

Counters can be decremented rather than incremented Here is a program with a loop. It contains a while statement, followed by a block of code. A block is a group of statements enclosed in braces. // Example of a while loop decrementing public class WhileLoopExample public static void main (String[] args ) int count = 2; // count is initialized while ( count >= 0 ) // count is tested System.out.println( "count is:" + count ); count = count - 1; // count is changed by -1 System.out.println( "Done counting down." ); 8

The do-while Statement Here is a program with a loop. It contains a do statement, followed by a block of code, followed by a while statement. // Example of a do-while loop public class DoWhileExample public static void main (String[] args ) int count = 1000; // initialize do System.out.println( count ); count++ ; // change s after the entire block is executed while ( count < 10 ); // test System.out.println( "Done with the loop" ); 9

The Basic Syntax of the do-while Statement do statement1; statement2; o 0 0 statementn; while (condition); 10

Basic Terminology of the do-while Statement The condition is a Boolean expression: something that evaluates to true or false. The condition can be complicated, using many relational operators and logical operators. A single statement is allowed Without braces to create a block only one statement is executed inside the loop The block or single executable statement is sometimes called the loop body. The do-while is always executed at least once, if the do statement is executed There is a semi-colon after the while statement in a dowhile 11

The for Statement Here is a program with a loop. It contains a for statement, followed by a block of code. A block is a group of statements enclosed in braces. // Example of a for loop public class ForExample public static void main (String[] args ) int sum=0; for ( int count = 0; count <= 5; count++ ) sum = sum + count ; System.out.print( count + " " ); System.out.println( \nsum is: " + sum ); Initialization count = 0 loop condition count <= 5 sum = sum + count Print count count++ Print sum false 12

The Basic Syntax of the for Statement for (initialization; loop condition; update statements) statement1; statement2; o 0 0 statementn; 13

Basic Terminology of the for Statement initialization Used to initialize basic variables used in the loop condition More than one variable can be set, separated by commas You can declare the variable in the for statement, but then it is only valid within the for loop that it is created for for (int j=3, k=4; ; ) If no variables are set, you must have a ; before the loop condition this typically means that the variable has been set prior to the for statement The initialization portion of the for statement is only executed once, each time you enter the loop loop condition A boolean expression evaluates as true or false Evaluated at the beginning of each loop Although this statement can be left out, leaving it out could lead to an infinite do loop, unless you execute a break statement inside the loop 14

Basic Terminology of the for Statement (2) update statement(s) Increases or decreases a value, typically one or more used in the loop condition Should always executed at the end of the loop body that s why we use postfix Can include more than one statement, separated by commas for( ; ; i++, j= j+5) Notes: If you are eliminating multiple parts of a for statement it may be better to use a while or do-while Don t stuff too many extraneous things into the for statement, you ll confuse yourself 15

Nested Loops A nested loop is a (inner) loop that appears in the loop body of another (outer) loop. The inner or outer loop can be any type: while, do while, or for. For example, the inner loop can be a while loop while an outer loop can be a for loop. Of course, they can be the same kind of loops too. Inner loops always stay completely inside their outer loops An inner loop may be skipped over during the execution of an outer loop For instance, if the loop is inside of an if block that isn t executed, then that loop wouldn t be executed 16

Nested Loop Example // Example of nested loop public class NestedLoops public static void main (String[] args ) int height =5; int width = 4; for ( int i = 0 ; i < height ; i++ ) for ( int j = 0 ; j< width ; j++ ) System.out.print( "*" ) ; System.out.println( "" ) ; Now let s look at the MultTable Example 17

The break statement Used to exit the innermost loop that the break is found within, unless the loop is labeled Loop is labeled with looplabelname: followed by the loop Next statement executed is the first statement beyond the scope of that loop If you label a loop the break statement can be used to exit through an outer nesting We ll look at BreakLabeledLoop.java 18

The flag or sendnel A flag or sentinel is a value appended to a data collection that signals the end of the data. The idea of a sentinel controlled loop is that there is a special value (the sentinel) that is used to control when the loop is done. In following code fragment, the user enters a zero when the sum is complete. Zero is the sentinel. Here is how the program should work import java.util.scanner; // Add up integers entered by the user. // After the last integer, the user enters a 0. class AddUpNumbers public static void main (String[] args ) Scanner keyboard = new Scanner( System.in ); int value, sum = 0; System.out.print( "Enter first integer (enter 0 to quit): " ); value = keyboard.nextint(); //we initialize value before entering the loop while ( value!= 0 ) sum = sum + value; System.out.print( "Enter next integer (enter 0 to quit): " ); value = keyboard.nextint(); //update value inside the loop System.out.println( "Sum of the integers: " + sum ); 19

Bad Input data There are cases when erroneous data is entered There are many options Request revised data Exit the program In order to do either you must check the data first Note: Some inputs will cause the program to crash Can you name 0ne? We will look at GeneralAverage in a few minutes 20

Scope of a Variable (1) A variable s scope is determined by the highest level of braces within which it is defined. It works at that level and all nested level If you use the same variable name in an outer and nested blocks, an error will occur. If you exit a block where a variable is defined you can reuse the variable name It s values are separate from the originally named variable Don t use the same variable name twice in a program it only confuses things. You are allowed to continuously redeclare a variable in the same statement with a loop Scope is extremely important to understand in nested loops. Once you leave the loop a variable declared in the loop no longer exists. 21

Scope of a Variable (2) / Demonstrate block scope. class Scope public static void main(string args[]) int n1; // Visible in main n1 = 10; if(n1 == 10) // start new scope int n2 = 20; // visible only to this block // n1 and n2 both visible here. System.out.println("n1 and n2 : "+ n1 +""+ n2); // n2 = 100; // Error! n2 not known here // n1 is still visible here. System.out.println("n1 is " + n1); 22

Scope of a Variable (3) class LifeTime public static void main(string args[]) int i; for(i = 0; i < 3; i++) int y = -1; System.out.println("y is : " + y); Variable y is declared inside for loop block. Each time when control goes inside For loop Block, Variable is declared and used in loop. When control goes out of the for loop then the variable becomes inaccessible. 23

Scope of a Variable (4) class ScopeInvalid public static void main(string args[]) int num = 1; // creates a new scope int num = 2; // Compile-time error // num already defined class ScopeValid public static void main(string args[]) // creates a new scope int num = 1; // creates a new scope int num = 2; 24

Programming Exercises Class (1) Exercise 2 Pictures Write a program that reads an integer n and prints the following right triangle with base and height n 1 x 2 xx 3 xxx 4.. n xxxxxx.x 25

Programming Exercises Class(2) Exercise 9 GeneralAverage Write a program that calculates the average of n test scores, such that each score is an integer in the range 0 to 100. Your program should first prompt for an integer n and then request n scores. Your program should also test for invalid data. If a user enters a number outside the correct range, the program should prompt for another value. Round the average to the closest integer. 26

Programming Exercises Lab (1) Exercise 3 MorePictures Write a program that accepts an integer n and prints out the following picture of a diamond with 2n-1 rows 1 X 2 X X X 3 X X X X X n XXXXXXXXXXX (2n-1 times). 2n-1 X 27

Programming Exercises Lab (2) Exercise 10 Modified Average Write a program that accepts a list of n test scores, and then finds the average of the n-1 highest scores on the list that is, the lowest score on the list is not included in the average. For example, if the test scores are 90, 80, 70, and 60, the average is computed as (90 + 80+70)/3. The low score of 60 is excluded Your program should first prompt for an integer n and then request n scores. Your program should also test for invalid data. If a user enters a number outside the correct range, the program should prompt for another value. Round the average to the closest integer. 28