Flow of Control: Loops

Similar documents
Flow of Control: Loops. Chapter 4

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

Flow of Control: Loops

4. Flow of Control: Loops. Objectives. Java Loop Statements: Outline 10/3/11. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich

4. Flow of Control: Loops

4. Flow of Control: Loops

4. Flow of Control: Loops. Objectives. Java Loop Statements 10/10/12. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich

Flow of Control. Chapter 3. Chapter 3 1

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

Repetition and Loop Statements Chapter 5

STUDENT LESSON A12 Iterations

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

Repetition, Looping. While Loop

Loops / Repetition Statements

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

SECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

CS110D: PROGRAMMING LANGUAGE I

Repetition CSC 121 Fall 2014 Howard Rosenthal

Supplement: Visual C++ Debugging

MEDIA COMPUTATION DRJAVA. Lecture 11.3 November 7, 2008

ECE 122. Engineering Problem Solving with Java

Flow Control. CSC215 Lecture

Chapter Goals. Contents LOOPS

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

Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Introduction to Programming Using Java (98-388)

Repetition, Looping CS101

A Tutorial for ECE 175

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

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Repetition Structures

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

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

CS1004: Intro to CS in Java, Spring 2005

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

Flow of Control. Chapter 3

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

Intro to MS Visual C++ Debugging

Chapter 17. Iteration The while Statement

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

Lecture 5 Tao Wang 1

Control Flow Statements

Problem Solving With Loops

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

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

Chapter 3. Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

C++ Programming: From Problem Analysis to Program Design, Third Edition

Lesson 1. Introduction to Programming OBJECTIVES

Lecture 10. Daily Puzzle

Chapter 5: Loops and Files

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved.

COMP Introduction to Programming If-Else Statement, Switch Statement and Loops

Lab 8 - Vectors, and Debugging. Directions

REPETITION CONTROL STRUCTURE LOGO

Loops / Repetition Statements

Example: Monte Carlo Simulation 1

Quiz Determine the output of the following program:

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

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

Debugging in Small Basic is the process of analysing a program to detect and fix errors or improve functionality in some way.

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

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

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

Information Science 1

The for Loop. Lesson 11

Information Science 1

Loops (while and for)

More on control structures

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

Looping. Arizona State University 1

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

THE JAVA FOR STATEMENT

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

5. Control Statements

Lecture 7 Tao Wang 1

CS1150 Principles of Computer Science Loops (Part II)

Chapter 4 Introduction to Control Statements

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

Lecture 3 Tao Wang 1

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

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

7 The Integrated Debugger

CS112 Lecture: Repetition Statements

3chapter C ONTROL S TATEMENTS. Objectives

2.8. Decision Making: Equality and Relational Operators

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -CONTROL FLOW : LOOP- SPRING 2015, SEON-JU AHN, CNU EE

Computer Programming I - Unit 5 Lecture page 1 of 14

Loops. Variable Scope Remapping Nested Loops. Donald Judd. CS Loops 1. CS Loops 2

Programming for Engineers Iteration

int j = 0, sum = 0; for (j = 3; j <= 79; j++) { sum = sum + j; System.out.println(sum); //Show the progress as we iterate thru the loop.

The following expression causes a divide by zero error:

1.00 Lecture 2. What s an IDE?

Transcription:

Walter Savitch Frank M. Carrano Flow of Control: Loops Chapter 4

Java Loop Statements: Outline The while statement The do-while statement The for Statement

Java Loop Statements A portion of a program that repeats a statement or a group of statements is called a loop. The statement or group of statements to be repeated is called the body of the loop. A loop could be used to compute grades for each student in a class. There must be a means of exiting the loop.

The while Statement Also called a while loop A while statement repeats while a controlling boolean expression remains true The loop body typically contains an action that ultimately causes the controlling boolean expression to become false.

The while Statement Syntax while (Boolean_Expression) { First_Statement Second_Statement }

The while Statement Download, compile, and run WhileDemo

The do-while Statement Also called a do-while loop Similar to a while statement, except that the loop body is executed at least once Syntax do { Body_Statement(s) } while (Boolean_Expression); Don t forget the semicolon!

The do-while Statement Figure 4.3 The action of the do-while loop in DoWhileDemo

The do-while Statement First, the loop body is executed. Then the boolean expression is checked. As long as it is true, the loop is executed again. If it is false, the loop is exited. Equivalent while statement Statement(s)_S1 while (Boolean_Condition) { Statement(s)_S1 }

Using while to Read Input Download WhileWithScanner.java from the Examples link on the course webpage Compile and run a few times until you are comfortable with what the program does and how it does it.

Exercise Modify WhileWithScanner.java so that it reads one line of doubles, prints the intermediate results, and finally prints the sum for the entire line. Read a whole line from keyboard into a String Create a Scanner object on that String Proceed as before, but with the new Scanner

Infinite Loops A loop which repeats without ever ending is called an infinite loop. If the controlling boolean expression never becomes false, a while loop or a do-while loop will repeat without ending. Make sure a loop contains a statement which causes the boolean expression to become false eventually.

Nested Loops The body of a loop can contain any kind of statements, including another loop.

Exercise Modify WhileWithScanner.java Add an outer loop that reads an entire line of input The inner loop calculates the sum for the current line of input

The for Statement A for statement executes the body of a loop a fixed number of times. Example for (count = 1; count < 3; count++) { System.out.println(count); }

The for Statement Syntax for (Initialization; Condition; Update) Body_Statement Body_Statement can be either a simple statement or a compound statement in {}. Corresponding while statement Initialization while (Condition) Body_Statement_Including_Update

The for Statement Download ForDemo

The for Statement Possible to declare variables within a for statement int sum = 0; for (int n = 1 ; n <= 10 ; n++) { sum = sum + n; } Note that variable n is local to the loop

Exercise Write a program called ReverseWords that reads lines of text from the keyboard and prints the line backwards Example: input: what's up? output:?pu s'tahw

Controlling Number of Loop Iterations If the number of iterations is known before the loop starts, the loop is called a count-controlled loop. Use a for loop. Asking the user before each iteration if it is time to end the loop is called the ask-before-iterating technique. Appropriate for a small number of iterations Use a while loop or a do-while loop.

The break Statement in Loops A break statement can be used to end a loop immediately. The break statement ends only the innermost loop or switch statement that contains the break statement. break statements make loops more difficult to understand. Use break statements sparingly (if ever).

The break Statement in Loops Note program fragment, ending a loop with a break statement, listing 4.8

The continue Statement in Loops A continue statement Ends current loop iteration Begins the next one Text recommends avoiding use Introduces unneeded complications

Tracing Variables Tracing variables means watching the variables change while the program is running. Simply insert temporary output statements in your program to print of the values of variables of interest Or, learn to use the debugging facility that may be provided by your system.

Tracing Variables with Drjava Open WhileWithScanner.java Choose Debugger->Debug Mode A new panel is added with Stack and Thread tabs Right-click on the code sum += num; and choose Toggle Breakpoint That line now has a red background

Tracing Variables with Drjava Click on the left-right arrows to the left of the Stack tab A new panel is added with a Watches tab Type num into the Name field and hit return Type sum into the next Name field, then return Run the program and type some numbers when promted to do so The program will stop at the breakpoint and show the values of num and sum

Tracing Variables with Drjava Click the Step Over button to move to the next statement Click the Resume button to move to the next breakpoint To exit the debugger and the program, click the Reset button located on the top panel

Loop Bugs Common loop bugs Unintended infinite loops Off-by-one errors Testing equality of floating-point numbers Subtle infinite loops The loop may terminate for some input values, but not for others. Example: you can t get out of debt when the monthly penalty exceeds the monthly payment.