Simple Programs

In this chapter, you’ll learn what a computer program is, about the program counter, how to use functions, and how to write your own functions.

A computer program is made up of instructions that a computer follows. There are many different programming languages. We will learn the programming language Javascript and some HTML and CSS, languages used to describe web pages. The instructions that make up a computer program are called the program’s source code, or code for short.

Why Javascript?

Javascript shares many similarities with other programming languages, including Python, Java and C++, and once you’ve learned Javascript, these other languages will not be difficult to pick up. Javascript is the language that your browser uses to add interactive elements to web pages, and it’s an integral part of most business-oriented web pages.

Code example: print

Here is our first program. It prints the number 42:

You can run the program by pressing the arrow button directly above the window that contains the program.

This program causes the computer to print the number 42 to a window (more on this window later). The function print is provided to us by Javascript. The parameter 42 is specified by us the programmer. The semicolon at the end of the command signifies the end of the command.

Here is another program:

In this multi-line program, commands are executed in the order they appear. Each statement in this program produces its output in a new line of the window; run the program to see the output.

Code example: printing text

The program:

causes the computer to print the word hello. Notice that the quotation marks around hello are not printed. They indicate that we want a string of five characters to be printed. As with printing numbers, we can print multiple strings on separate lines:

The program counter

When your computer runs a program, there’s actually a program called an interpreter that runs the program. The interpreter reads each line of the program, interprets what the line instructs the computer to do, and then executes that interpretation.

As the interpreter runs a program, the interpreter keeps track of the line number that is currently being executed, much as you might use a bookmark to keep track of what page you’re reading in a book. The bookmark that the computer uses to keep track of the line number is called the program counter.

The program counter always starts out pointing at the first line of the code in the program you run. It executes that line of code. Depending on what that line of code says, one of two things happens:

Why would we ever want the interpreter to suddenly jump to a new line of code? We’ll see many reasons, but the first is to write and use our own commands – functions – that are made up of a chunk of lines of code. By giving a name to a chunk of lines of code, we can easily reuse that section of code without having to retype all those lines every time.

Writing your own functions

Let’s define our own function, sayHello:

Run the above code. Nothing is printed because we have only defined a function – we have not run the function. To run this program, we call the function. To tell the interpreter to actually run the body of a function, you use a function call. To write a function call, write the name of the function followed by parentheses:

Think of a cookbook containing various recipes. The printed recipes are like function definitions: they tell how to prepare a dish when you decide to prepare it, but they don’t, on their own, cause the dish to be prepared. Actually preparing a dish by following the recipe is like a function call.

Function definitions have two parts: a header, and a body. The header gives the name of the function you want to define (as well as some other things that we’ll see later). The body is a sequence of lines of code that tell what the function does. By convention, each line of the body is indented. The indentations make the code more readable by us, but have no effect on how the computer interprets the code.

The header uses var, the name of the function you’d like to define, an equal sign, function(), and an open curly bracket. A matching closing curly bracket at the end of the body specifies the end of the function body. Notice also the semicolon after the closing curly bracket. As with the print statements, this semicolon signifies the end of the command (in this case, the definition of a function). (You might be wondering why we have parentheses with nothing between them. We’ll soon see that we can put parameters—which provide information necessary for the function to do its job—between the parentheses.)

function is an example of a keyword in javascript: a word that has special meaning in a program. Keywords may not be used for any other purpose; for example, you cannot give a function the name function.

So the header of our function is:

var sayHello = function() {

and the body is:

print( "I say hello." );

We can define multiple functions:

Now we can call these functions at will. Notice that we can interlace calls to our functions (sayHello and sayGoodbye) with calls to built-in Javascript functions (print).

Exercise: hello, hello!

Objective: Write and call your own functions to learn how the program counter steps through code.

You will write a program that introduces you and prints your favorite number.

  1. Write the body of the function printFavoriteNumber
  2. Write a function call at the end of the program that calls printFavoriteNumber.
  3. Write a new function, sayIntroduction that prints Hello, my name is X. and I am a Y. on two separate lines, where X and Y are replaced by whatever you like.
  4. Add a line that calls sayIntroduction so that the introduction is printed before the favorite number.

Test your code after steps 2 and 4: take a minute to think through what you expect to happen, and then press the run button.

Here is a solution. No peeking until you have solved it yourself!

Abstraction: the value of (temporary) ignorance

When we build higher-level concepts from simpler pieces and then work with those higher-level concepts, we are taking advantage of abstraction. Abstraction is a major tool in computer science that we’ll come back to over and over.

Abstraction hides the details of how things work. Functions are our first example of abstraction.

We defined two functions, each in terms of a sequence of simpler commands. Once we defined those functions, we were able to just use them without thinking (too much) about how they worked. Here’s another big win for functions. You can use a function someone else wrote, without knowing exactly the internal details of the function.

Abstraction helps us in areas beyond computer science. For example, when I press the gas pedal on my car, a lot of stuff happens, but because I have the higher-level “push-gas-pedal-car-moves” concept, I don’t have to think about the details of what is going on in the drive train (engine, transmission, differential, etc.) to make my car go.

The function sayHello is a trivial example of an abstraction. Let’s look at a more interesting example. I have defined a function called showTime which prints the current time. I can call the function:

Once I tell you that you have access to the function showTime() and describe what it does, you can use it without worrying about, or even knowing, how it works.

Function parameters

Just like the print command, functions can take parameters: additional information that influences what the function does. When making a function call, we write the values of the parameters inside the parentheses. We say that we pass the parameters to the function at the point of call. Functions may take multiple parameters, in which case we separate them by commas when we call the function. Here’s an example:

The function rect is passed four parameters. The first two parameters, 50 and 50, specify where to draw the upper left corner of the square. The second two parameters, 75 and 100, specify the width and height of the square to draw (we’ll describe in more detail precisely how these numbers are specified).

Here is a longer example:

The function fill specifies the color of the rectangles drawn by the function rect. The function fill takes thee parameters: each parameter is a number between 0 and 255 and specifies the fraction of red, green, and blue (in that order) that, when mixed together, form the color. White would be (255, 255, 255), black would be (0, 0, 0), pure red would be (255, 0, 0), pure yellow would be (255, 255, 0) (mixing red and green), and so forth. Play with changing the parameters to fill in the above program and rerun the program to paint different colored rectangles.

Notice that the last two squares on the right overlap each other. This is because our graphics rendering paints into the window without any knowledge of what was drawn before – so the order in which you call the functions matter.

For example, to make a four-level square bullseye, I would start with the largest green square, followed by blue, red, and then the smallest yellow square:

In this example, I specified the fill color before each call to rect. Each call to fill simply overrides the previous call and sets the fill color for all subsequent calls to rects.

Libraries

Sofware libraries are collections of functions intended to serve a particular related purpose. For example, the rect and fill functions are not built in to Javascript; they were written by someone else. All of the graphics commands used in this lecture are all from the processing.js library.

There are many, many libraries. For example, jquery provides functions that manipulate the elements of a web page, and I used it on this very web page that you are looking at to insert the cool boxes where you can type and run code. The Google Maps API provides functions that let you display and manipulate maps on a web page.

Libraries are a great example of abstraction.

Exercise: smile

Objective: learn how to call drawing library functions that take parameters, in order to draw a desired complex picture.

Write a program that causes a yellow smiley face to be drawn on the screen. You have a 200 by 200 window available.

  1. Draw the outline of the face. Put your code for drawing the outline after the line // draw the outline of the face. (Lines that begin with // are ignored by the computer, and are for human readers only. You can use the ellipse function described on the processing.js page.

  2. Draw the eyes. Put your code for drawing the eyes after the line // draw the eyes.

  3. Bonus challenge. Draw the mouth. Hint – draw a circle, and then erase the top part of it by drawing some sort of yellow shape.

Here is a solution. No peeking until you have solved it yourself!

Graphics coordinates

We glossed over what the coordinates passed to the drawSquare function really means. When drawing in a graphics window, there’s a coordinate system within the window. Coordinates correspond to pixels in the window, with (0, 0) at the upper left corner of the window.

The coordinates (100, 75) mean the pixel that is 100 pixels to the right and 75 pixels below the upper left corner. Think of it this way: starting from the upper left corner of the graphics window, x coordinates increase to the right, and y coordinates increase down from the top. If you think about how x and y coordinates usually work in mathematics, graphics on a computer doesn’t quite match up. The x direction works, but in math, increasing y coordinates go up, whereas in computer graphics, increasing y coordinates go down.