Computer Science. 4. Input and Output. 4. Input and Output. Computer Science. Standard input and output. Standard drawing Fractal drawings Animation

Similar documents
1.3 Conditionals and Loops

1. Writing Simple Classes:

1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright /6/11 12:33 PM!

University of Pennsylvania. Electrical & Systems Engineering Undergraduate Laboratories. ESE 112: Introduction to Electrical & Systems Engineering

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

J a v a Quiz (Unit 3, Test 0 Practice)

Using Files as Input/Output in Java 5.0 Applications

2.3 WINDOW-TO-VIEWPORT COORDINATE TRANSFORMATION

Building Java Programs

WAYNESBORO AREA SCHOOL DISTRICT CURRICULUM INTRODUCTION TO COMPUTER SCIENCE (June 2014)

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Introduction to Java

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

1.1 Your First Program

Java Programming Fundamentals

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Sources: On the Web: Slides will be available on:

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

13 File Output and Input

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Crash Course in Java

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Chapter 1 Java Program Design and Development

Java Basics: Data Types, Variables, and Loops

dictionary find definition word definition book index find relevant pages term list of page numbers

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Lecture 5: Java Fundamentals III

6.1. Example: A Tip Calculator 6-1

Java Crash Course Part I

1001ICT Introduction To Programming Lecture Notes

CS 3530 Operating Systems. L02 OS Intro Part 1 Dr. Ken Hoganson

CS 106 Introduction to Computer Science I

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to programming

AP Computer Science Java Mr. Clausen Program 9A, 9B

Basics of I/O Streams and File I/O

Building Java Programs

Programmierpraktikum

Chapter 2: Elements of Java

AP Computer Science Java Subset

PROG0101 Fundamentals of Programming PROG0101 FUNDAMENTALS OF PROGRAMMING. Chapter 3 Algorithms

Using WINK to create custom animated tutorials

Definition: A vector is a directed line segment that has and. Each vector has an initial point and a terminal point.

2 SYSTEM DESCRIPTION TECHNIQUES

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

Chapter 3. Input and output. 3.1 The System class

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Patterns in Pascal s Triangle

Unit 7 Quadratic Relations of the Form y = ax 2 + bx + c

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

MXwendler Javascript Interface Description Version 2.3

System Calls and Standard I/O

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Example of a Java program

7 th Grade Math Foundations for Teaching Unit One: Numbers & Operations Module One: Rational Number s

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Stage 5 Information and Software Technology

Invitation to Ezhil : A Tamil Programming Language for Early Computer-Science Education 07/10/13

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

C# and Other Languages

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Stacks. Data Structures and Data Types. Collections

Mathematical Ideas that Shaped the World. Chaos and Fractals

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

CPLEX Tutorial Handout

An Introduction to Computer Science

Install Java Development Kit (JDK) 1.8

public static void main(string[] args) { System.out.println("hello, world"); } }

MATLAB Functions. function [Out_1,Out_2,,Out_N] = function_name(in_1,in_2,,in_m)

Illustration 1: Diagram of program function and data flow

DATA 301 Introduction to Data Analytics Microsoft Excel VBA. Dr. Ramon Lawrence University of British Columbia Okanagan

MATH 60 NOTEBOOK CERTIFICATIONS

How to Build a Simple Pac-Man Game

INTRODUCTION TO DIGITAL SYSTEMS. IMPLEMENTATION: MODULES (ICs) AND NETWORKS IMPLEMENTATION OF ALGORITHMS IN HARDWARE

While Loops and Animations

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

C++ Input/Output: Streams

cs2010: algorithms and data structures

Marist School Computational Media. Processing Exercise 01 Bouncing Ball Animation. Description:

Creating a Simple, Multithreaded Chat System with Java

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Computer Science III Advanced Placement G/T [AP Computer Science A] Syllabus

Variables, Constants, and Data Types

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

In this Chapter you ll learn:

Object-Oriented Programming in Java

Chapter One Introduction to Programming

Outline. hardware components programming environments. installing Python executing Python code. decimal and binary notations running Sage

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Mathematics as Problem Solving The students will demonstrate the ability to gather information from a graphical representation of an equation.

Euler s Method and Functions

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Input and Interaction

Transcription:

Computer Science 4. Input and Output Standard input and output 4. Input and Output Computer Science Standard drawing Fractal drawings Animation An Interdisciplinary Approach.5 ROBERT SEDGEWICK K E V I N WAY N E http://introcs.cs.princeton.edu CS.4.A.IO.Standard Basic building blocks for programming Input and output Goal: Write s that interact with the outside world via input and output devices. any program you might want to write Typical INPUT devices objects functions and modules Keyboard Trackpad Storage Camera Network Microphone graphics, sound, and image I/O Typical OUTPUT devices arrays conditionals and loops Math primitive data types Ability to interact with the outside world Storage text I/O Network Printer Speakers Display Our approach. assignment statements Define input and output abstractions. Use operating system (OS) functionality to connect our s to actual devices. 3 4

Abstraction Quick review plays an essential role in understanding computation. Interested in thinking more deeply about this concept? Consider taking a philosophy course. Terminal. An abstraction for providing input and output to a program. An abstraction is something that exists only as an idea. Example: "Printing" is the idea of a program producing text as output. Input from command line % java DrawCards Good abstractions simplify our view of the world, by unifying diverse real-world artifacts. 7 Q A Q Q 6 5 Output to standard output stream Virtual VT- terminal This lecture. Abstractions for delivering input to or receiving output from our programs. 5 Input-output abstraction (so far) 6 Review: command-line input Command-line input. An abstraction for providing arguments (strings) to a program. A mental model of what a does. command-line arguments Basic properties Strings you type after the program name are available as args[], args[],... at run time. Arguments are available when the program begins execution. Need to call system conversion methods to convert the strings to other types of data. public class RandomInt int N = Integer.parseInt(args[]); double r = Math.random(); int t = (int) (r * N); System.out.println(t); standard output stream 7 % java RandomInt 6 3 % java RandomInt 384 8

Review: standard output Improved input-output abstraction Infinity. An abstraction describing something having no limit. Add an infinite input stream. Standard output stream. An abstraction for an infinite output sequence. command-line arguments standard input stream Basic properties Strings from System.out.println() are added to the end of the standard output stream. Standard output stream is sent to terminal application by default. public class RandomSeq int N = Integer.parseInt(args[]); for (int i = ; i < N; i++) System.out.println(Math.random()); % java RandomSeq 4.93744678469.47958739575.89946576994.657979663546435 No limit on amount of output % java RandomSeq.947488944943.8397433847.8339645856476.9577577344.8359857659798.7469443738.5835677583997.3455796587455... standard output stream 9 Standard input StdIn library Developed for this course, but broadly useful Implement abstractions invented for UNIX in the 97s. Available for download at booksite. Included in introcs software you downloaded at the beginning of the course. Standard input stream. An abstraction for an infinite input sequence. Computer Science Infinity. An abstraction describing something having no limit. Computer Science An Interdisciplinary Approach ROBERT SEDGEWICK K E V I N WAY N E standard input stream public class StdIn boolean isempty() int readint() double readdouble() long readlong() boolean readboolean() Advantages over command-line input Can provide new arguments while the program is executing. char readchar() No limit on the amount of data we can input to a program. Conversion to primitive types is explicitly handled (stay tuned). true iff no more values read a value of type int read a value of type double standard input stream read a value of type long read a value of type boolean read a value of type char String readstring() read a value of type String String readall() read the rest of the text

StdOut library StdIn/StdOut warmup Implement abstractions invented for UNIX in the 97s. Available for download at booksite. Included in introcs software you downloaded at the beginning of the course. Computer Science Developed for this course, but broadly useful Interactive input Prompt user to type inputs on standard input stream. Computer Science Mix input stream with output stream. An Interdisciplinary Approach ROBERT SEDGEWICK K E V I N WAY N E public class AddTwo StdOut.print("Type the first integer: "); int x = StdIn.readInt(); StdOut.print("Type the second integer: "); int y = StdIn.readInt(); int sum = x + y; StdOut.println("Their sum is " + sum); public class StdOut void print(string s) put s on the output stream void println() put a newline on the output stream void println(string s) put s, then a newline on the stream void printf(string f,...) formatted output standard output stream Q. These are the same as System.out. Why not just use System.out? A. We provide a consistent set of simple I/O abstractions in one place. use StdOut from now on % java AddTwo Type the first integer: Type the second integer: Their sum is 3 A. We can make output independent of system, language, and locale. 3 StdIn application: average the numbers on the standard input stream Average Read a stream of numbers. Compute their average. Q. How do I specify the end of the stream? A. <Ctrl-d> (standard for decades). A. <Ctrl-z> (Windows). Key points No limit on the size of the input stream. Input and output can be interleaved. 4 Summary: prototypical applications of standard output and standard input StdOut: Generate a stream of random numbers public class Average double sum =.; // cumulative total int n = ; // number of values while (!StdIn.isEmpty()) double x = StdIn.readDouble(); sum = sum + x; n++; StdOut.println(sum / n); public class RandomSeq int N = Integer.parseInt(args[]); for (int i = ; i < N; i++) StdOut.println(Math.random()); StdIn: Compute the average of a stream of numbers public class Average double sum =.; // cumulative total int n = ; // number of values while (!StdIn.isEmpty()) double x = StdIn.readDouble(); sum = sum + x; n++; StdOut.println(sum / n); Both streams are infinite (no limit on their size). % java Average. 5. 6. 3. 7. 3. <Ctrl-d>.5 Q. Do I always have to type in my input data and print my output? A. No! Keep data and results in files on your computer, or use piping to connect programs. 5 6

Redirection: keep data in files on your computer Piping: entirely avoid saving data Redirect standard output to a file % java RandomSeq > data.txt % more data.txt.947488944943.8397433847.8339645856476.9577577344.8359857659798.7469443738.5835677583997.3455796587455... "redirect standard output to" Redirect from a file to standard input % java Average < data.txt.49476555677499 "take standard input from" Q. There's no room for a huge file on my computer. Now what? A. No problem! Use piping. Piping. Connect standard output of one program to standard input of another. % java RandomSeq java Average.49979747368 % java RandomSeq java Average.5787564484 set up a pipe RandomSeq RandomSeq standard output stream standard input stream Average standard output stream file standard input stream Slight problem. Still limited by maximum file size. Average 7 Critical point. No limit within programs on the amount of data they can handle. It is the job of the system to collect data on standard output and provide it to standard input. 8 Streaming algorithms Early computing Amount of available memory was much smaller than amount of data to be processed. But dramatic increases happened every year. Redirection and piping enabled programs to handle much more data than computers could store. Image sources http://www.digitalreins.com/wp-content/uploads/3/5/binary-code.jpg PART I: PROGRAMMING IN JAVA http://en.wikipedia.org/wiki/punched_tape#mediaviewer/file:harwell-dekatron-witch-.jpg Modern computing Amount of available memory is much smaller than amount of data to be processed. Dramatic increases still happen every year. Streaming algorithms enable our programs to handle much more data than our computers can store. Lesson. Avoid limits within your program whenever possible. 9 CS.4.A.IO.Standard

Further improvements to our I/O abstraction Add the ability to create a drawing. command-line arguments standard input stream 4. Input and Output Standard input and output Standard drawing Fractal drawings standard output stream standard drawing Computer Science Animation StdDraw library Computer Science An Interdisciplinary Approach ROBERT SEDGEWICK K E V I N WAY N E Developed for this course, but broadly useful. Available for download at booksite. Included in introcs software. CS.4.B.IO.Drawing StdDraw library Hello, World for StdDraw public class StdDraw public class Triangle double c = Math.sqrt(3.) /.; StdDraw.setPenRadius(.); StdDraw.line(.,.,.,.); StdDraw.line(.,.,.5, c); StdDraw.line(.5, c,.,.); StdDraw.point(.5, c/3.); StdDraw.text(.5,.5, "Hello, World"); void line(double x, double y, double x, double y) void point(double x, double y) void text(double x, double y, String s) void circle(double x, double y, double r) also filledcircle(), filledsquare(), and filledpolygon() void square(double x, double y, double r) void polygon(double x, double y, double r) void picture(double x, double y, String filename) place.gif,.jpg or.png file void setpenradius(double r) void setpencolor(color c) void setxscale(double x, double x) reset x range to [x, x) void setyscale(double y, double y) reset y range to [y, y) void show(int dt) show all; pause dt millisecs Trace of drawing (.5,.8665...) Hello, World (, ) (, ) standard drawing 3 4

Hello, World for StdDraw window for standard drawing public class Triangle double c = Math.sqrt(3.) /.; StdDraw.setPenRadius(.); StdDraw.line(.,.,.,.); StdDraw.line(.,.,.5, c); StdDraw.line(.5, c,.,.); StdDraw.point(.5, c/3.); StdDraw.text(.5,.5, "Hello, World"); % % javac Triangle.java % java Triangle virtual terminal for editor read coords of bounding box StdDraw application: data visualization public class PlotFilter double xmin = StdIn.readDouble(); rescale read and plot a point double ymin = StdIn.readDouble(); double xmax = StdIn.readDouble(); double ymax = StdIn.readDouble(); StdDraw.setXscale(xmin, xmax); StdDraw.setYscale(ymin, ymax); while (!StdIn.isEmpty()) double x = StdIn.readDouble(); double y = StdIn.readDouble(); StdDraw.point(x, y); % more < USA.txt 66995. 475. 4496. 49. 9738.889 4555.778 396. 4733.333 4677.778 475.556... % java PlotFilter < USA.txt bounding box coords sequence of point coordinates (3,59 cities) virtual terminal for OS commands 5 6 StdDraw application: plotting a function Goal. Plot y =sin(4x)+sin(x) in the interval (, π). Method. Take N samples, regularly spaced. % java PlotFunctionEx PART I: PROGRAMMING IN JAVA public class PlotFunctionEx int N = Integer.parseInt(args[]); double[] x = new double[n+]; double[] y = new double[n+]; for (int i = ; i <= N; i++) x[i] = Math.PI * i / N; y[i] = Math.sin(4*x[i]) + Math.sin(*x[i]); StdDraw.setXscale(, Math.PI); StdDraw.setYscale(-., +.); for (int i = ; i < N; i++) StdDraw.line(x[i], y[i], x[i+], y[i+]); Lesson : Plotting is easy. % java PlotFunctionEx Lesson : Take a sufficiently large sample otherwise you might miss something! 7 CS.4.B.IO.Drawing

StdDraw application: a random game Draw an equilateral triangle, number the vertices,, and make the current point. 3 4 5 6 7 8 9 Pick a vertex at random. Draw a point halfway between that vertex and the current point. 4. Input and Output Repeat. Standard input and output Standard drawing Fractal drawings vertex ID probability new x new y (, ) /3.5x.5y Animation (, ) /3.5x +.5.5y (.5, 3/) /3.5x +.5.5y +.433 CS.4.C.IO.Fractals 3 StdDraw application: a random game public class Chaos int trials = Integer.parseInt(args[]); Sierpinski triangles in the wild % java Chaos double c = Math.sqrt(3.) /.; double[] cx =.,.,.5 ; double[] cy =.,., c ; StdDraw.setPenRadius(.); double x =., y =.; for (int t = ; t < trials; t++) int r = (int) (Math.random() * 3); x = (x + cx[r]) /.; y = (y + cy[r]) /.; StdDraw.point(x, y); odd numbers 3 6 4 5 5 6 5 5 6 7 35 35 7 3 4 Pascal's triangle 3 3

Iterated function systems Iterated function systems What happens when we change the rules? probability new x Another example of changing the rules % java IFS < coral.txt new y probability new x %.5 4%.3x.53y +.89.46x.9y +. 5%.3x.8y +..5x.45y +.34 5%.69x.y +.38 3%.7x 7%.78x +.3y +. 45%.55y +. IFS.java (Program..3) is a data-driven program that takes the coefficients from standard input. % more coral.txt 3.4.5.45 3 3.3769 -.53469.3769 -.7693..545455 3 3 -.46538 -.9376.53846 -.44755.6938 -.9584.4x +.6y +.57.y +.4 % java IFS < barnsley.txt new y.7y.5x +.y -.4.x +.8y +.9.3x +.74y +.7 % more barnsley.txt 4..5.3.7 4 3...5 -.39.63.57.7 -.5.48.78.34.75 4 3..7..46.4 -.36..76.893 -.3.739.7.8863493.669.6363.96865.338376.38854 33 34 Iterated function systems Simple iterative computations yield patterns that are remarkably similar to those found in the natural world. Image sources Q. What does computation tell us about nature? http://paulbourke.net/fractals/gasket/cokegasket.gif an IFS fern a real fern http://www.buzzfeed.com/atmccann/-awesome-math-foods#39wokfk http://sheilakh.deviantart.com/art/the-legend-of-sierpinski-38953447 Q. What does nature tell us about computation? http://commons.wikimedia.org/wiki/file:lady_fern_frond_-_normal_appearance.jpg http://img3.wikia.nocookie.net/ cb777/jamescameronsavatar/images/e/e/avatar_concept_art-3.jpg th century sciences. Formulas. st century sciences. Algorithms? a real plant an IFS plant Note. You have seen many practical applications of integrated function systems, in movies and games. 35 CS.4.C.IO.Fractals

PART I: PROGRAMMING IN JAVA Animation To create animation with StdDraw. rx+vx Repeat the following: 4. Input and Output Standard input and output Standard drawing Fractal drawings Animation Clear the screen. Move the object. Draw the object. Display and pause briefly. When display time is much greater than the screen-clear time, we have the illusion of motion. Bouncing ball. Ball has position (rx, ry) and constant velocity (vx, vy). To move the ball, update position to (rx+vx, ry+vy). ry rx vy vx ry+vy If the ball hits a vertical wall, set vx to -vx. If the ball hits a horizontal wall, set vy to -vy. CS.4.D.IO.Animation 38 Bouncing ball Pop quiz on animation public class BouncingBall double rx =.48, ry =.86; double vx =.5, vy =.3; double radius =.5; StdDraw.setXscale(-., +.); StdDraw.setYscale(-., +.); while(true) StdDraw.setPenColor(StdDraw.LIGHT_GRAY); StdDraw.filledSquare(.,.,.); if (Math.abs(rx + vx) + radius >.) vx = -vx; if (Math.abs(ry + vy) + radius >.) vy = -vy; rx = rx + vx; ry = ry + vy; StdDraw.setPenColor(StdDraw.BLACK); StdDraw.filledCircle(rx, ry, radius); StdDraw.show(); % java BouncingBall Q. What happens if we move clear the screen out of the loop? public class BouncingBall double rx =.48, ry =.86; double vx =.5, vy =.3; double radius =.5; StdDraw.setXscale(-., +.); StdDraw.setYscale(-., +.); while(true) StdDraw.setPenColor(StdDraw. LIGHT_GRAY); StdDraw.filledSquare(.,.,.); if (Math.abs(rx + vx) + radius >.) vx = -vx; if (Math.abs(ry + vy) + radius >.) vy = -vy; rx = rx + vx; ry = ry + vy; StdDraw.setPenColor(StdDraw.BLACK); StdDraw.filledCircle(rx, ry, sz); StdDraw.show(); 39 4

Pop quiz on animation Deluxe bouncing ball Q. What happens if we move clear the screen out of the loop? public class BouncingBall double rx =.48, ry =.86; double vx =.5, vy =.3; double radius =.5; StdDraw.setXscale(-., +.); StdDraw.setYscale(-., +.); StdDraw.setPenColor(StdDraw. LIGHT_GRAY); StdDraw.filledSquare(.,.,.); while(true) if (Math.abs(rx + vx) + radius >.) vx = -vx; if (Math.abs(ry + vy) + radius >.) vy = -vy; rx = rx + vx; ry = ry + vy; StdDraw.setPenColor(StdDraw.BLACK); StdDraw.filledCircle(rx, ry, radius); StdDraw.show(); public class BouncingBallDeluxe double rx =.48, ry =.86; double vx =.5, vy =.3; double radius =.5; StdDraw.setXscale(-., +.); StdDraw.setYscale(-., +.); while(true) StdDraw.setPenColor(StdDraw. LIGHT_GRAY); StdDraw.filledSquare(.,.,.); if (Math.abs(rx + vx) + radius >.) StdAudio.play("pipebang.wav"); vx = -vx; if (Math.abs(ry + vy) + radius >.) StdAudio.play("pipebang.wav"); vy = -vy; rx = rx + vx; ry = ry + vy; StdDraw.picture(rx, ry, "TennisBall.png"); StdDraw.show(); A. We see the ball s entire path. % java BouncingBallDeluxe Stay tuned to next lecture for full description of StdAudio. 4 4 A set of I/O abstractions for Java StdIn, StdOut, StdDraw, and StdAudio. Available for download at booksite (and included in introcs software). Computer Science Developed for this course, but broadly useful Computer Science An Interdisciplinary Approach ROBERT SEDGEWICK K E V I N WAY N E command-line arguments standard input stream standard output stream standard drawing standard audio 43 CS.4.D.IO.Animation

Computer Science Computer Science An Interdisciplinary Approach.5 ROBERT SEDGEWICK K E V I N WAY N E http://introcs.cs.princeton.edu 4. Input and Output