Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

Similar documents
Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

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

Java Bytecode (binary file)

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Loops. CSE 114, Computer Science 1 Stony Brook University

MIDTERM REVIEW. midterminformation.htm

Introduction to Programming Using Java (98-388)

Following is the general form of a typical decision making structure found in most of the programming languages:

Lec 7. for loops and methods

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

CS 102 / CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2010

TESTING AND DEBUGGING

Java Tutorial. Saarland University. Ashkan Taslimi. Tutorial 3 September 6, 2011

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

Give one example where you might wish to use a three dimensional array

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

PROGRAMMING FUNDAMENTALS

Introduction to Java & Fundamental Data Types

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

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

Array. Prepared By - Rifat Shahriyar

( &% class MyClass { }

Lecture 15. Arrays (and For Loops)

Java Basic Programming Constructs

Programming in the Small II: Control

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

STUDENT LESSON A12 Iterations

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Simple Java Reference

Lecture 14. 'for' loops and Arrays

CS111: PROGRAMMING LANGUAGE II

Chapter 4 Loops. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

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

CP122 CS I. Iteration

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

The Java language has a wide variety of modifiers, including the following:

CSE 114 Midterm 1. Please leave one seat between yourself and each of your neighbors.

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

CT 229 Java Syntax Continued

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

Introduction to Programming (Java) 4/12

Module 5. Arrays. Adapted from Absolute Java, Rose Williams, Binghamton University

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014

Course Outline. Introduction to java

Expressions & Flow Control

Nested Loops. A loop can be nested inside another loop.

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

C: How to Program. Week /Mar/05

CSE 142 Su 04 Computer Programming 1 - Java. Objects

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

CS 231 Data Structures and Algorithms, Fall 2016

Dept. of CSE, IIT KGP

CSE 8A Lecture 21. SMarx extra final exam office hours Fri 3/15 11:15am-1pm EBU-3B #2206

York University Department of Electrical Engineering and Computer Science. Regular Expressions

Object-Oriented Programming

Lecture Set 4: More About Methods and More About Operators

2.8. Decision Making: Equality and Relational Operators

CMPT 125: Lecture 4 Conditionals and Loops

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

An overview of Java, Data types and variables

Computer Programming, I. Laboratory Manual. Final Exam Solution

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

CHAPTER 7 OBJECTS AND CLASSES

AP Computer Science Unit 1. Programs

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM

3. Java - Language Constructs I

CS 101 Fall 2005 Midterm 2 Name: ID:

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Chapter 2 - Introduction to C Programming

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

13 th Windsor Regional Secondary School Computer Programming Competition

Lecture 22: Java. Overall Structure. Classes & Objects. Every statement must end with ';' Carl Kingsford, , Fall 2015

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Topics. Chapter 5. Equality Operators

This exam is open book. Each question is worth 3 points.

Programming Projects: 2.1, 2.3, 2.4, 2.7, 2.8, 2.13

CHAPTER 7 OBJECTS AND CLASSES

I. True/False: (2 points each)

Announcements. Lab 03 inbase late submissions Midterm #1 Friday. Project 2 is posted. Covers everything through basics of OOP

Repetition Structures

Inheritance and Interfaces

What does this program print?

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

1 Lexical Considerations

CS 102/107 - Introduction to Programming Midterm Exam #2 - Prof. Reed Spring 2011

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

CS1004: Intro to CS in Java, Spring 2005

University of Palestine. Mid Exam Total Grade: 100

IS 0020 Program Design and Software Tools

Transcription:

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

General Loops in Java Look at other loop constructions Very common while loop: do a loop a fixed number of times (MAX in the example) int count = 0; while (count < MAX) count ++;

for loop int count; for (count=0; count < MAX; count++) The loop parameters are upfront A succinct way to say do the following MAX times You don't have to just increment by 1 DiagonalLoopGray2.java

for loop general form int count; for (initial statement; test condition; update statement) The loop parameters are upfront - Don't have to read to the bottom of the loop to figure out is a standard counting loop single digit letters are commonly used for loop indices. DiagonalLoopGray2.java

How is for loop translated into a while loop? for (initial statement; test condition; update statement) initial statement; while ( test condition) This is Translated to: update statement;

For loop steps 1)Initial statement executed 2)termination statement evaluated 3)if!terminated then execute statements execute update statement Go back to step 2)

The Loop Index for (count=0; count < MAX; count++) count is the loop index, takes on values 0, 1,2, 3, 4,..,MAX 1

You don't have to just count up you can count Down for (count=max; count > 0; count ) count ( the loop index ), takes on values MAX, MAX -1, MAX -2,, 1 NOTE: the difference between this and previous Both perform MAX loops loop index is off by one Always need to check starting and ending index for errors (important for Arrays in next lecture) This is a common bug in loops

MAX + 1 iterations for (count=0; count <= MAX; count++) count ( the loop index ), takes on values 0,1,2,, MAX NOTE: MAX + 1 iterations get used to counting starting from 0, very common in Java and C

Common Error for (count=0; count <= MAX; count++); count ( the loop index ), takes on values 0,1,2,, MAX Processing statements executed exactly ONCE one ; can ruin your whole day :-(

Subversive but legal public class Subversive private static final int MAX=20; public static void main(string [] args) int count, j = 0; for (count=0; count++ <= MAX; j++) System.out.format("%d %d\n", count, j); Confusing takes longer to figure out what it does Can you guess the output? This might be a little too clever :-)

Loops with non-integer indexes Legal, but you may not get exactly what you expect for (double count=0; count < MAX; count += 0.33333) count is the loop index, takes on values 0.0, 0.33333, 0.66666, 0.99999, 1.33332, 1.66665,. May not be exactly what you intended because doubles are only approximations of real numbers This is called round-off error When using non-integer loop indices, never check for exact equality as the termination condition. e.g. count!=.999999)

Do...While do while (condition); Do loop guaranteed to be executed at least once DoWhileEx.java

NestedLoops Just like nested while loops You can nest a for loop inside of while loop and vice-versa. When we do two-dimensional arrays, nested loops are quite common Use this on your homework due friday Nest can go arbitrarily deep, but seldom do you see more than three levels. Knitting.java example from book

break and continue break and continue are special keywords used inside of loops break immediately stop processing the loop, go to first statement that follows the entire loop. continue stop processing this iteration of the loop. If a for loop, execute the update statement, then go to the top of the loop. While/do While, go to the top of the loop Why write code with break and/or continue? special handling of particular cases become apparent

A common use of break Code is searching for the first occurrence of a particular condition, but will only search for so long. for (int i = 0; i < MAX; i++) if (Function(i) < 0) if (i < MAX) else break; System.out.println(i); System.out.println( Function is >= 0

Common Use of Continue You only want to process occurrences that have (or have not) met a condition Student pupil; Course myclass; while ((pupil = myclass.nextstudent())!= null) if (!pupil.tookmidterm()) continue; // only proces if midterm was taken. grade = pupil.computegrade(); myclass.record(pupil.getname(),grade); pupil.emailgrade(grade);

Formatted Printing System.out.format( format string, value1, value2,, valuen) Method supports a variable number of arguments format string has replaceable format elements The first replaceable element is assigned value1, the second value2, and so on. %<char> is a placeholder for the type for format to perform %d format as an integer %f format as floating point number %s format as a string

Special Characters in the Format string \n newline \t tab \r return (no new line) Example strings %d : %f \n print first arg as an int, second as a float, print a newline. System.out.format( %d : %f \n, j, vx); Can specify fixed width, too %5d would format an integer using at least 5 spaces a good cheat-sheet of format codes http://alvinalexander.com/programming/printf-format-cheat-sheet Example: FormatMe.java