CIS 234: LOOPS Adapted from materials by Dr. Donald Bell, 2000 (updated April 2007)

Slides:



Advertisements
Similar presentations
CHAPTER 5: Repetition Control Structure. Objectives  To develop algorithms that use DOWHILE and REPEAT.. UNTIL structures  Introduce a pseudocode for.
Advertisements

Computer Science 1620 Loops.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Chapter 5: Control Structures II (Repetition)
Repetition Statements repeat block of code until a condition is satisfied also called loops Java supports 3 kinds of loops: while statement – repeats a.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Chapter 4: Control Structures II
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 4 Objectives  Learn about repetition (looping) control structures.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
New Tools And Workshop Mod & For Loops. Modulo Calculates the remainder (remember long division?) % Examples: 7 % 3 10 % 2 2 % 3 evaluates to 1 evaluates.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
Repetition Structures Repetition Structures allow you to write programs that will repeat program steps multiple times. –Also called Loops –Counter controlled.
Chapter 4: Control Structures II
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Chapter 5: Control Structures II
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Control Structures II: Repetition.  Learn about repetition (looping) control structures  Explore how to construct and use count-controlled, sentinel-controlled,
Using Java MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE OF SCIENCE AND TECHNOLOGY KHANYOUNIS- PALESTINE Lecture 9 & 10 Repetition Statements.
JavaScript, Fourth Edition
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
COMP Loop Statements Yi Hong May 21, 2015.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Chapter 6: Looping. Objectives Learn about the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Loops Tonga Institute of Higher Education. Introduction Programs need to be able to execute tasks repeatedly. Use loops to repeat actions  For Loop 
Lecture 4b Repeating With Loops
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II
Lecture 6 Repetition Richard Gesick.
CS161 Introduction to Computer Science
Chapter 5: Control Structures II
Chapter 3 Loops Section 3.3 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 5: Control Structures II
Loop Structures.
Repetition-Counter control Loop
Java Programming: Guided Learning with Early Objects
Control Statements Kingdom of Saudi Arabia
Control Structures - Repetition
Lecture 4A Repetition Richard Gesick.
MSIS 655 Advanced Business Applications Programming
Outline Altering flow of control Boolean expressions
Repetition Statements (Loops) - 2
Based on slides created by Bjarne Stroustrup & Tony Gaddis
PROGRAM FLOWCHART Iteration Statements.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

CIS 234: LOOPS Adapted from materials by Dr. Donald Bell, 2000 (updated April 2007)

What is a Loop? A structure that will execute a line or block of code a number of (i.e., zero to many) times based on predetermined criteria Also called iteration or repetition

LOOPS All languages need an iteration statement Recall that Bohm and Jacopini stated that all computer solvable problems need only three types of structures: Sequence Selection Iteration (loop)

Loops in Java Purpose of a loop is to execute a group of lines (1 or more) a number of (0 to many) times A block gets repeated recall that a block is 1 or more simple Java statements if more than 1 line, surrounded by curly braces also called a compound Java statement a block can contain any number or type of statements block can also contain conditional logic, or other loops

Loops Can Have: Initialization Test to exit the loop Statements in the body of the loop Increment or other statement that will change the value that determines whether you will stay in the loop Some loops omit some of these The order of these may vary

Statements that Build Loops in Java Three (or is that 2?) statement types for while do... while

Under What Conditions Do You Use Each? forwhen you want to initialize a variable at the beginning of the loop and increment or change it after each iteration whilewhen initialization and/or increments are not done by the loop do … whilesame as while but used when you want to execute the body of the loop at least once. This is the "test after" loop

Structure of the "for" loop for (init-expr; bool-expr; increment-expr) statement-1 where statement-1 could be simple or compound Examples: for (int count = 1; count < 5; count = count + 1) amount = amount + payroll [count] ; for (int count = 1; count < 5; ++count) //shortcut { total = total + sale [count]; } // block could contain multiple lines

Structure of "for" Statement Structure: for (initialization-expression; boolean-expression; increment-expression) Example: for (counter = 1; counter < 50; counter = counter + 1) Explanation: initializationcounter = 1 //or int counter = 1 establishes the control variable, in this case, counter boolean-expressioncounter < 50 specifies the test for staying in the loop increment-expressioncounter = counter + 1 specifies the amount by which the control variable (i.e., counter) will be changed after each pass through the body of the loop

"for" Statement Structure - 2 "for" is lower case the three parameters are surrounded by parentheses the three parameters are separated by semi-colons need to provide space for all three parameters to be identified (some could be empty e.g., ; ;) no punctuation follows the closing parenthesis i.e., no ; (no semicolon)

"for" Loop Execution Steps Initialization Test Body of Loop Increment Test Body of Loop Increment Test …. continues until boolean in Test step evaluates to false; then goes to statement after the loop

Examples of "for" Loops for ( int count = 0; count < 10 ; count ++) System.out.println (count); for ( int count = 0; count < 10 ; count ++) { System.out.println ("iteration # = " + count); System.out.println (Math.sqrt(count)); }

Missing "for" Parameters int i = 0; // initialization for ( ; i<10 ; ) // both ; still there { i++; // incrementing System.out.println(i); } // hardly ever do it this way

"for" Loop Practice Write a for statement that makes the control variable counter start at one and take each of the values 1, 2, … up to 100 Add an action statement to the loop that will add up these numbers (total of 1 through 100) Modify the loop to add up the even numbers between 1 and 100 (2+4+6 etc.)

Structure of a "while" Loop while (boolean-expression) statement-1 where statement-1 can be: simple (one statement followed by semicolon) compound (multiple statements inside curly braces)

Structure of the "while" Statement while ( count < 3 ) while starts with a lower case letter the boolean expression is enclosed in parentheses and can be simple or complex NO punctuation following the closing parenthesis ( no ; in this "line")

"while" with No Block basic while (without a block) int stopAt = [user input]; int count = 1; while ( count <= stopAt ) count++; note: count ++ means count = count + 1

"while" with a Block while with a block int count = 0; while ( count < stopAt ) { count ++; System.out. println("count = " + count); }

while Practice Write code and a while statement that makes a variable start at one and take each of the values 1, 2, … up to 100 Add an action statement to the loop that will add up these numbers (total of 1 through 100) Modify the loop to add up the numbers between 1 and 100 that are divisible by 3 (3+6+9 etc.)

"do … while" Loop "do … while" loop has the test at the end Example: do {… //statements in body of loop answer = JOptionPane.showInputDialog("More?"); } while (answer.charAt(0).toUpperCase() == 'Y'); Note: remember to put ; after while test

When Do You Use a "do … while" Loop? Very useful when need to ask the question at the end of the loop You use this when you know you want to execute the body of the loop at least once Examples: Do you want to enter another customer? (after processing 1 st customer) Keep adding items while total/result is less than what you need (keep pumping gas as long as tank is not full)

"do... while" Practice Write a do... while loop that will read in an integer value using JOptionPane, and verify that it is between 1 and 9 If value is not between 1-9, prompt the user to enter the value, with word "again" added to the prompt text Note: an example of JOptionPane syntax is on previous slide

Comparing "for" and "while" Statements for (init-expr-1; bool-expr-1; incr-expr-1) { statement-1 } becomes init-expr-1; while (bool-expr-1) { statement-1 incr-expr-1 } Which is better? When? Why?

Avoid "Infinite Loops" Make sure that the test will eventually stop its loop the value that the boolean expression tests must eventually get to a stopping point if the test never stops the loop, the computer will "lock up" and not do anything else use "break" ([Ctrl] C in DOS window) to halt program if it won't end

Summary Java has selection and iteration statements similar to most computer languages Java's selection and iteration statements are much like C++ There are several types of iteration statements for different circumstances Java iteration statements can use either simple statements or blocks -- but blocks (have { }) are much less likely to be misunderstood Writing loops gets easier with practice