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