Repetition CSC 121 Fall 2014 Howard Rosenthal

Similar documents
Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Control Statements Review CSC 123 Fall 2018 Howard Rosenthal

Chapter 4: Control structures. Repetition

Chapter 4: Control structures

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

STUDENT LESSON A12 Iterations

Repetition and Loop Statements Chapter 5

Repetition, Looping CS101

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

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

Repetition Structures

Introduction. C provides two styles of flow control:

Controls Structure for Repetition

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

Introduction to the Java Basics: Control Flow Statements

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

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

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

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

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

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

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

REPETITION CONTROL STRUCTURE LOGO

Top-Down Program Development

Computer Programming I - Unit 5 Lecture page 1 of 14

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

Flow of Control: Loops. Chapter 4

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

LECTURE 5 Control Structures Part 2

Chapter Goals. Contents LOOPS

Problem Solving With Loops

Java Coding 3. Over & over again!

Methods CSC 121 Fall 2016 Howard Rosenthal

Looping. Arizona State University 1

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

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

204111: Computer and Programming

Chapter 5: Loops and Files

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

Principles of Computer Science I

Loops. CSE 114, Computer Science 1 Stony Brook University

Iteration statements - Loops

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

CS 106 Introduction to Computer Science I

Chapter 17. Iteration The while Statement

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

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

Chapter 4: Making Decisions

Loops / Repetition Statements

A Look Back at Arithmetic Operators: the Increment and Decrement

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

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

Chapter 4: Making Decisions

CS 106 Introduction to Computer Science I

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

Lecture 7 Tao Wang 1

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Methods CSC 121 Spring 2017 Howard Rosenthal

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

Repetition with for loops

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

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Dept. of CSE, IIT KGP

CSC 1051 Data Structures and Algorithms I

ECE 122. Engineering Problem Solving with Java

Flow of Control: Loops

! 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

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

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Loops. GEEN163 Introduction to Computer Programming

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

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

CS112 Lecture: Repetition Statements

The for Loop. Lesson 11

CS110D: PROGRAMMING LANGUAGE I

LECTURE 04 MAKING DECISIONS

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

Methods CSC 121 Fall 2014 Howard Rosenthal

Text Input and Conditionals

Control Structures II. Repetition (Loops)

AP Programming - Chapter 6 Lecture

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

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Recap: Assignment as an Operator CS 112 Introduction to Programming

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

Last Class. While loops Infinite loops Loop counters Iterations

Introduction to Java & Fundamental Data Types

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

n Group of statements that are executed repeatedly while some condition remains true

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Flow of Control: Loops. Objectives. Java Loop Statements: Outline 6/27/2014. Chapter 4

Loops and Files. of do-while loop

Flow Control. CSC215 Lecture

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

3chapter C ONTROL S TATEMENTS. Objectives

Transcription:

Repetition CSC 121 Fall 2014 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

Fundamental Loops Each type of loop can be built using the while, do-while or for statements. The 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 brackets. // 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 unless there is an exit condition 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 brackets 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 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 brackets. // 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 brackets 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 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 brackets. // 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 Always executed at the end of the loop body 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 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 sentinel 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(); while ( value!= 0 ) sum = sum + value; System.out.print( "Enter next integer (enter 0 to quit): " ); value = keyboard.nextint(); 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

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 21

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. 22

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 23

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. 24