Principles of Computer Science I

Similar documents
Repetition Structures

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

Chapter 5: Loops and Files

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

Lab 11. A sample of the class is:

Chapter 4 Introduction to Control Statements

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

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

STUDENT LESSON A12 Iterations

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.

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Loops / Repetition Statements

Recitation: Loop Jul 7, 2008

HST 952. Computing for Biomedical Scientists Lecture 8

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

Repetition, Looping. While Loop

Why Is Repetition Needed?

Repetition, Looping CS101

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Chapter 4: Control structures. Repetition

CSCE 206: Structured Programming in C++

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

Chapter Goals. Contents LOOPS

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

Chapter 4: Loops and Files

Introduction. C provides two styles of flow control:

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

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

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

Chapter 4: Loops and Files

Chapter 4: Control structures

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

Loops. CSE 114, Computer Science 1 Stony Brook University

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Loop structures and booleans

(Refer Slide Time: 00:26)

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

3 The L oop Control Structure

REPETITION CONTROL STRUCTURE LOGO

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

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

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

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

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Overview CSE 143. Input and Output. Streams. Other Possible Kinds of Stream Converters. Stream after Stream... CSE143 Wi

Computer Programming I - Unit 5 Lecture page 1 of 14

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

CS 106 Introduction to Computer Science I

Lab 5: Java IO 12:00 PM, Feb 21, 2018

CS 170 Java Programming 1. Week 10: Loops and Arrays

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

CS110D: PROGRAMMING LANGUAGE I

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

Conditionals and Loops

Simple Java Input/Output

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Au

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp

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

ECE 122. Engineering Problem Solving with Java

Byte and Character Streams. Reading and Writing Console input and output

Information Science 1

Repetition and Loop Statements Chapter 5

e) Implicit and Explicit Type Conversion Pg 328 j) Types of errors Pg 371

5. Control Statements

A sample print out is: is is -11 key entered was: w

CS111: PROGRAMMING LANGUAGE II

Lesson 3: Accepting User Input and Using Different Methods for Output

Loops (while and for)

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

LOOPS. Repetition using the while statement

Looping. Arizona State University 1

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

Question 1. (2 points) What is the difference between a stream and a file?

Flow Control. CSC215 Lecture

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

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Java Review. Fundamentals of Computer Science

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

while (condition) { body_statements; for (initialization; condition; update) { body_statements;

CS 112 Introduction to Programming

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

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

Classes Basic Overview

Chapter 3: Program Statements

Information Science 1

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

204111: Computer and Programming

CS 106 Introduction to Computer Science I

Chapter 4: Conditionals and Loops

CSC Java Programming, Fall Java Data Types and Control Constructs

Introduction Unit 4: Input, output and exceptions

Dept. of CSE, IIT KGP

CS1004: Intro to CS in Java, Spring 2005

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

Transcription:

Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120A - Fall 2004 Lecture Unit 7 Review Chapter 4 Boolean data type and operators (&&,,) Selection control flow structure if, if-else, nested if structures Testing, algorithm walk-though, execution trace Encapsulation and abstraction CSC 120A - Berry College - Fall 2004 2 File Input/Output Up till now, we have been interacting with our programs through screen and keyboard It is also useful to be able to input and output data using a file on disk instead Using a file for input allows us to: Handle large quantities of data Type a little bit at a time Go back and fix mistakes Can re-run the program with the same data without having to retype it Using a file for output we can View output on the screen or print it Examine output without having to re-run the program Store data that is used as input for another program Five Steps to File IO 1. Import Java library: java.io.* 2. Declare file variable identifier 3. Instantiate file object and assign to the file variable 4. Use methods of the file object to read or write data 5. Call a method to close the file when we are done CSC 120A - Berry College - Fall 2004 3 CSC 120A - Berry College - Fall 2004 4 File IO: Step 1 import java.io.*; We already know how to do that For files, we will be using the FileReader, FileWriter, BufferedReader, and PrintWriter classes from the library FileReader and FileWriter provide basic functionality of reading/writing one character at a time PrintWriter allows us to output data to a file just like we ve been outputting data to the screen with the System.out object CSC 120A - Berry College - Fall 2004 5 File IO: Step 2 PrintWriter outfile; BufferedReader infile; Declare file identifiers like any other variable BufferedReader for input files, PrintWriter for output files These classes work with character stream files (files that we view and change in a text editor) Data is organized in lines (sequences of characters) Each line ends with an EOL (end-of-line) mark that editor doesn t display it goes to the next line as it places characters on the screen CSC 120A - Berry College - Fall 2004 6

File IO: Step 3 outfile = new PrintWriter(new FileWriter( outfile.txt )); infile = new BufferedReader(new FileReader( infile.txt )); Create file objects for use in your program and associate them with physical files on the disk With input file: file pointer is placed at the first character in the file With output file: creates a new empty file, or erases old contents of existing file File IO: Step 4 (Output) outfile.print( The answer is + 49); outfile.println( Rate = + rate); Just like System.out.print and println println() adds an EOL mark to the end of the string as it is saved in the file CSC 120A - Berry College - Fall 2004 7 CSC 120A - Berry College - Fall 2004 8 File IO: Step 4 (Input) String line = infile.readline(); int num = Integer.parseInt(inFile.readLine()); Exactly like reading data from the keyboard, because we are using the same BufferedReader class readline() discards the EOL mark as it is reading a line of characters from the file returns null if we ve reached the end of file (EOF) We can skip over a bunch of letters in a file: infile.skip(100l); // L means it s a long integer literal Throws an exception if we try to skip past the end of the file Need to include throws IOException clause after methods that use these input methods CSC 120A - Berry College - Fall 2004 9 File IO: Step 5 infile.close(); outfile.close(); Breaks the association between the physical file and the variable (infile/outfile) Makes file available for use by other programs Be nice: close files once you are done with them A simple program using files (UseFile.java) CSC 120A - Berry College - Fall 2004 10 Looping Control structure that causes a statement or group of statements to be executed repeatedly Pattern: while ( <boolean-expression> ) <statement> Example: while ( count <= 25 ) count = count + 1; Body of a loop can be single statement or a group of statements enclosed in { CSC 120A - Berry College - Fall 2004 11 Flow Charts false if (b) statement1; statement2; true b? statement1 statement2 b? statement1 true false statement2 if (b) statement1; else statement2; statement3; false statement1 while (b) statement1; statement2; CSC 120A - Berry College - Fall 2004 12 b? statement3 true statement2

Loop Terminology Loop entry: point at which flow of control reaches first statement inside a loop Iteration: an individual pass through, or repetition of, the body of a loop Loop test: point at which while expression is evaluated to decide whether to loop or not Loop exit: point at which control passes to first statement after the loop body Termination condition: condition that causes loop to be exited Types of Loops Count-controlled loop: a loop that executes a specified number of times Event-controlled loop: loop that terminates when something happens inside the body to signal that the loop should be exited Making an angel food cake: Beat the mixture 300 strokes (count-controlled loop) Cut with a pastry blender until the mixture resembles coarse meal (event-controlled loop) CSC 120A - Berry College - Fall 2004 13 CSC 120A - Berry College - Fall 2004 14 Count-Controlled Loops Use a variable (loop control variable) in the test Before entering the loop, must initialize the loop control variable In each iteration of the loop, must update (usually increment by 1) the loop control variable int loopcount = 1; while (loopcount <= 10) { loopcount = loopcount + 1; Example: Count-Controlled Loop int mult = 1; while (mult <= 10) { System.out.println( 2 times + mult + is + (2 * mult)); mult++; // same as: mult = mult + 1; Redo BinaryConv.java using a loop If you forget to properly initialize or update the loop control variable your program will go into the famous infinite loop. CSC 120A - Berry College - Fall 2004 15 CSC 120A - Berry College - Fall 2004 16 Event-Controlled Loops Loops often used to read in and process long lists of data Amount of data is unknown so we cannot use a count-controlled loop Instead, we read/process data until some special data value is reached, or until the end of file A sentinel (or trailer) value in a file is used as a signal that the end of data to be processed has been reached E.g. In a program that reads in a calendar dates, we may use the date February 31 as a sentinel Loop with a Sentinel Value String date = infile.readline(); // priming read while (!date.equals( 0231 ) ) { date = infile.readline(); Priming read: before entering the loop, we must read the first data value At the end of the loop body, read in the next data value CSC 120A - Berry College - Fall 2004 17 CSC 120A - Berry College - Fall 2004 18

Reading Until EOF String line = infile.readline(); // priming read while ( line!= null ) { line = infile.readline(); null is a special Java constant value; think of it as referring to a non-existent address null is not equivalent to an empty String CSC 120A - Berry College - Fall 2004 19 Tasks Accomplished by Looping Counting Keep track of the number of times loop is executed Summation Computing the sum of a set of data values Exercise: Write a program to read in integers from a file, temperature.txt, compute their average as a double value, and print the average on the screen Exercises: Redo the BinaryConv and ISBNDigit programs we wrote earlier CSC 120A - Berry College - Fall 2004 20 From Textbook, pg. 232 Example of a flag-controlled loop count = 0; // Initialize event counter sum = 0; // Initialize sum notdone = true; // Initialize loop control flag while (notdone) { line = datafile.readline(); // Get a line if (line!= null) { // Got a line? number = Integer.parseInt(line);// Convert line to int if (number % 2 == 1) { // Is the int value odd? count++; // Yes increment counter sum += number; // Add value to sum notdone = (count < 10); // Update loop control flag else { errorfile.println( EOF reached unexpectedly. ); notdone = false; // Update loop control flag CSC 120A - Berry College - Fall 2004 21 Designing Loops Design flow of control 1. What condition ends the loop? 2. How should the condition be initialized? 3. How should the condition be updated? Design processing within loop body 4. What is the process being repeated? 5. How should the process by initialized? 6. How should the process be updated? Specify state upon loop exit 7. What is the state of code upon exiting the loop? CSC 120A - Berry College - Fall 2004 22 Designing Flow of Control Designing Process Within the Loop What makes the loop stop?. Problem Statement Termination condition. Sum 365 temperatures Counter reaches 365 (count-controlled loop) Process all data in the file EOF occurs (EOF-controlled) Process until 10 odd integers have 10 odd integers read been read (event counter) The end of the data is indicated Negative value encounby a negative test score tered (sentinel-controlled) Initialization and update Count-controlled: set iteration counter to 1; increment counter at end of each iteration Sentinel-controlled: open file, input initial value before entering the loop (priming read); input next value at end of each iteration Decide what a single iteration should do Count Sum Read data Perform calculation Print out something Initialize and update variables appropriately Flag-controlled: set boolean flag variable; update appropriately CSC within 120A -the Berry loop College as - Fall condition 2004 changes 23 CSC 120A - Berry College - Fall 2004 24

Loop Exit Check the condition of variables upon loop exit (especially check for off-by-one errors) linecount = 1; while ((inline = infile.readline())!= null) linecount++; System.out.println( There are + linecount + lines in the file. ); (above code is incorrect) CSC 120A - Berry College - Fall 2004 25 Nested Loops Create more complex and useful control structures (just like if statements) Initialize outer loop while ( Outer-loop-condition ) {... Initialize inner loop while ( Inner-loop-condition ) { Inner loop processing and update... CSC 120A - Berry College - Fall 2004 26 Example: Counting Commas in a File Partial program on page 236-237 Design loops using the seven steps on slide 22 Use the charat(n) method of the String class, which returns the character at a given position in the string ( ABCDE.charAt(0) returns A ) Exercise: How would you implement the MakeSpaces.spaces(n) method that we used in lab? public String spaces(int n) { Loop Testing and Debugging Develop test data for loops to check all possible scenarios Loop is skipped entirely Loop body executed exactly once Loop executes a normal number of times Loop fails to exit Check loop termination condition carefully Watch out for off-by-one errors Trace execution of loop by hand, step by step Use debugging output statements to isolate errors System.out.println( count = + count); Can be commented out later CSC 120A - Berry College - Fall 2004 27 CSC 120A - Berry College - Fall 2004 28 What s Wrong? Code segment to print out the even numbers between 1 and 15: What s Wrong II? Code segment to copy a line of text from one file to another, character by character: int n = 2; while (n!= 15) { n = n + 2; System.out.print(n + ); (2 logical errors) String line = infile.readline(); int count = 1; while (count < line.length()) { outfile.print(line.charat(count)); count++; outfile.println(); CSC 120A - Berry College - Fall 2004 29 CSC 120A - Berry College - Fall 2004 30

Asides Uninitialized variable error File types and extensions.txt.doc.in.out.pdf.ppt.html etc. Types of input Interactive vs. non-interactive Order of statements in a program Physical vs. logical Truth tables CSC 120A - Berry College - Fall 2004 31 Homework and Labs Be sure to include header comments on all program files you write Name, date, course, etc. A description of the class or program in the file Design issues, assumptions you made Comment methods and fields appropriately For example, the hundreds() method of the Check program Check programs 40 is spelled forty Rational number data type String constructor: public Rational(String str) { equals() method Comparing integers, you can use == Only use the Math.abs and TOLERANCE stuff if you have to compare double values Try to factor repeated blocks of code into a method (be lazy) CSC 120A - Berry College - Fall 2004 32