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

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

Top-Down Program Development

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

Selection and Repetition Revisited

Last Class. While loops Infinite loops Loop counters Iterations

Selection and Repetition

Selection and Repetition Revisited

Conditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Java I/O and Control Structures

Java I/O and Control Structures Algorithms in everyday life

Selection and Repetition

CSC 1051 Data Structures and Algorithms I

CMPT 125: Lecture 4 Conditionals and Loops

Loops / Repetition Statements

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

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

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

CSC 1051 Data Structures and Algorithms I

CS111: PROGRAMMING LANGUAGE II

Chapter 4: Control structures. Repetition

Java Coding 3. Over & over again!

Computer Science is...

COMP 202 Java in one week

CSC 1051 Data Structures and Algorithms I

Chapter 4: Control structures

COMP 202. Java in one week

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

COE 211/COE 212 Computer/Engineering Programming. Welcome to Exam II Thursday December 20, 2012

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

Iteration statements - Loops

Repetition CSC 121 Fall 2014 Howard Rosenthal

STUDENT LESSON A12 Iterations

Conditionals and Loops

CSCI 2010 Principles of Computer Science. Basic Java Programming. 08/09/2013 CSCI Basic Java 1

Loops / Repetition Statements

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

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 3: Program Statements

Mr. Monroe s Guide to Mastering Java Syntax

COE 212 Engineering Programming. Welcome to Exam II Tuesday November 28, 2018

Algorithms and Conditionals

Introduction to Computer Science Unit 2. Exercises

Repetition, Looping. While Loop

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

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

Selection Statements and operators

Selection Statements and operators

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

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

Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Data Structures COE 312 ExamII Preparation Exercises

Example: Monte Carlo Simulation 1

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

Recap: Assignment as an Operator CS 112 Introduction to Programming

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

Repetition Structures

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

Arrays. Eng. Mohammed Abdualal

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

CS 112 Introduction to Programming

Loops. Repeat after me

Bjarne Stroustrup. creator of C++

Practice Midterm 1 Answer Key

COMP-202 Unit 4: Programming with Iterations

Chapter 3. Selections

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

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

Over and Over Again GEEN163

COMP-202. Recursion. COMP Recursion, 2013 Jörg Kienzle and others

COE 212 Engineering Programming. Welcome to Exam II Thursday April 21, Instructors: Dr. Salim Haddad Dr. Joe Tekli Dr. Wissam F.

Repetition. Chapter 6

Repetition. Chapter 6

Chapter Goals. Contents LOOPS

CS111: PROGRAMMING LANGUAGE II

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

Controls Structure for Repetition

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

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

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

Assignment 2.4: Loops

Chapter 17. Iteration The while Statement

Using Classes and Objects

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

Introduction to Java & Fundamental Data Types

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

Warmup : Name that tune!

Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination

COMP 202. Programming With Arrays

Introduction to the Java Basics: Control Flow Statements

APCS Semester #1 Final Exam Practice Problems

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

Repetition with for loops

Exam 2, Version 2. For the following code, mark True or False for statements 1.8 to 1.10.

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

H212 Introduction to Software Systems Honors

Transcription:

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

Repetition Statements Repetition statements or iteration allow us to execute a statement multiple times repetitively They are often simply referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: the while loop, the do loop, and the for loop The programmer must choose the right kind of loop for the situation COMP 202 - Loops 2

Part 1 The WHILE Statement COMP 202 - Loops 3

The while Statement The while statement has the following syntax: while is a reserved word while ( condition ) statement; If the condition is true, the statement is executed. Then the condition is evaluated again. The statement is executed repetitively until the condition becomes false. COMP 202 - Loops 4

Logic of a while loop condition evaluated true statement false COMP 202 - Loops 5

The while Statement Note that if the condition of a while statement is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times COMP 202 - Loops 6

Counter.java public class Counter public static void main (String[] args) final int LIMIT = 5; int count = 1; while (count <= LIMIT) System.out.println (count); count = count + 1; System.out.println ("Done."); What does this print out? COMP 202 - Loops 7

BusPercentage.java final int NUM_SEATS = 56; int passengers; double ratio; Scanner scan = new Scanner(System.in); System.out.print ("Enter the number of passengers (0 to + NUM_SEATS + "): "); passengers = scan.nextint(); while (passengers < 0 passengers > NUM_SEATS) if (passengers > NUM_SEATS) System.out.print ("Too many...please reenter: "); else System.out.print ( That can t be...please reenter: "); passengers = scan.nextint(); ratio = (double)passengers / NUM_SEATS; DecimalFormat fmt = new DecimalFormat( 0.## ); System.out.println ("The bus is " + fmt.format(ratio*100) + % full."); How does this do what it does? COMP 202 - Loops 8

Infinite Loops The body of a while loop must eventually make the condition false If not, it is an infinite loop, which will execute until the user interrupts the program This is a common type of logical error You should always double check to ensure that your loops will terminate normally COMP 202 - Loops 9

Abyss.java public class Abyss public static void main (String[] args) int count = 1; System.out.println ("I'm going in..."); while (count <= Integer.MAX_VALUE) System.out.println (count); count = count - 1; System.out.println ("Found the bottom of the abyss!"); What is wrong here? Which statement is never reached? COMP 202 - Loops 10

Nested Loops Similar to nested if statements, loops can be nested as well That is, the body of a loop could contain another loop Each time through the outer loop, the inner loop will go through its entire set of iterations COMP 202 - Loops 11

PalindromeTester.java String str, another = "y"; int left, right; Scanner scan = new Scanner (System.in); while (another.equalsignorecase("y")) // allows y or Y System.out.println ("Enter a potential palindrome:"); str = scan.nextline(); left = 0; right = str.length() - 1; while (str.charat(left) == str.charat(right) && left < right) left++; right--; if (left < right) System.out.println ("That string is NOT a palindrome."); else System.out.println ("That string IS a palindrome."); System.out.print ("Test another palindrome (y/n)? "); another = scan.nextline(); Explain how this program works. COMP 202 - Loops 12

Part 2 The DO Statement COMP 202 - Loops 13

The do Statement The do statement has the following syntax: Uses both the do and while reserved words do statement; while ( condition ); The statement is executed once initially, then the condition is evaluated The statement is repetitively executed until the condition becomes false Do loops execute STATEMENT, always, at least once! COMP 202 - Loops 14

Logic of a do loop true statement condition evaluated false COMP 202 - Loops 15

Comparing the while and do loops while loop do loop condition evaluated true statement false true statement condition evaluated false COMP 202 - Loops 16

The do Statement A do loop is similar to a while loop, except that the condition is evaluated after the body of the loop is executed Therefore the body of a do loop will execute at least one time COMP 202 - Loops 17

Counter2.java public class Counter2 public static void main (String[] args) final int LIMIT = 5; int count = 0; do count = count + 1; System.out.println (count); while (count < LIMIT); System.out.println ("Done."); What does this print out? COMP 202 - Loops 18

ReverseNumber.java import java.util.scanner; public class ReverseNumber public static void main (String[] args) int number, lastdigit, reverse = 0; Scanner scan = new Scanner (System.in); System.out.print ("Enter a positive integer: "); number = scan.nextint(); do lastdigit = number % 10; reverse = (reverse * 10) + lastdigit; number = number / 10; while (number > 0); System.out.println ("That number reversed is " + reverse); How does this program work? COMP 202 - Loops 19

Part 3 The FOR Statement COMP 202 - Loops 20

The for Statement The for statement has the following syntax: Reserved word The initialization portion is executed once before the loop begins The statement is executed until the condition becomes false for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration COMP 202 - Loops 21

The for Statement A for loop is equivalent to the following while loop structure: initialization; while ( condition ) statement; increment; COMP 202 - Loops 22

Logic of a for loop initialization condition evaluated true statement increment false COMP 202 - Loops 23

The for Statement Like a while loop, the condition of a for statement is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times It is well suited for executing a specific number of times that can be determined in advance COMP 202 - Loops 24

Counter3.java public class Counter3 public static void main (String[] args) final int LIMIT = 5; for (int count=1; count <= LIMIT; count++) System.out.println (count); System.out.println ("Done"); What does this print out? COMP 202 - Loops 25

Multiples.java final int PER_LINE = 5; int value, limit, mult, count = 0; Scanner scan = new Scanner(System.in); System.out.print ("Enter a positive value: "); value = scan.nextint(); System.out.print ("Enter an upper limit: "); limit = scan.nextint(); System.out.println ("The multiples of " + value + " between " + value + " and " + limit + " (inclusive) are:"); for (mult = value; mult <= limit; mult += value) System.out.print (mult + "\t"); // Print a specific number of values per line of output count++; if (count % PER_LINE == 0) System.out.println(); What is this program doing? How? COMP 202 - Loops 26

Stars.java public class Stars public static void main (String[] args) final int MAX_ROWS = 10; for (int row = 1; row <= MAX_ROWS; row++) for (int star = 1; star <= row; star++) System.out.print ("*"); System.out.println(); What shape does this print out? COMP 202 - Loops 27

final int MAX_ROWS = 10; X.java for (int row = 1; row <= MAX_ROWS; row++) for (int space = 1; space <= MAX_ROWS-row; space++) System.out.print (" "); for (int star = 1; star <= row*2; star++) System.out.print ("*"); System.out.println (); for (int trunc=3; trunc>0; trunc--) for (int space = 1; space <= MAX_ROWS-1; space++) System.out.print (" "); System.out.println("**"); What shape does this print? COMP 202 - Loops 28

The for Statement Each expression in the header of a for loop is optional If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore creates an infinite loop If the increment is left out, no increment operation is performed Both semi-colons are always required in the for loop header COMP 202 - Loops 29

Part 4 Thinking Like A Programmer COMP 202 - Loops 30

Top-Down Program Development This refers to a way of thinking when you try to solve a programming problem: 1. First, read and understand the problem 2. Then, subdivide the problem into chunks. Each chunk is one task, like: initializing variables, inputs, outputs, ifstatements and loops. 3. Then order all these elements in the correct order. 4. Lastly, only now start writing your code Steps 1-3 are either done in your head or on scrap paper. They are not done using the language editor or compiler. They do not need to be in Java even, they could be in simple English/French/etc. COMP 202 - Loops 31

For Example Let me show you how to use top-down to solve: Make a program that asks the user for a positive integer number (at least 2). The program then displays that numbers and its greatest prime factor. The program repetitively does this until the user inputs a number less than 2. COMP 202 - Loops 32

Try This Problem Write a program that asks the user for a positive integer number (including zero). The program then displays a solid square followed by a hollow square. The program does nothing if the user inputs a negative value. N = 4 **** **** **** * * **** * * **** **** COMP 202 - Loops 33

Split the Problem Get the input and check for correctness A general solution for n >= 3 is clearly possible: How are the first and last line printed? How do you space solid from hollow text? How is a solid part of a square printed? How is a hollow part of a square printed? Print top, solid and hollow parts, and bottom What about n=0, 1, 2? Think of how your program will react COMP 202 - Loops 34