1. SUBPROGRAMS MAKE PROGRAMMING EASIER

In the previous lesson, you learned about logical control statements and loops that handle repetitive tasks. In this lesson, you learn about the use of subprograms and how they facilitate breaking complex programming problems into simpler parts. You also learn about a new topic, what programmers call IO -- short for Input and Output .

A subprogram encapsulates a programming chore in a small chunk of code that can be repeatedly used by other parts of your program. Without subprograms, tackling large problems would be impossible.

For example, suppose you have a chess program that has to draw the game board onscreen. It would be tedious to write the instructions to draw 64 individual squares with or without the chess piece images. Instead, you can create a subprogram to draw a square at a programmable location with a programmable image. Wherever your program has to repeat certain steps, you have a candidate for a subprogram.

Organizing all but the simplest programs in terms of subprograms results in code that's easier to understand and to maintain. It's also easier to improve because if you discover a faster way to draw images, for example, you only have to change one piece of code.

Different programming languages use different terms when talking about subprograms. Some commonly used terms are subroutine , procedure , method , and function . When you write the code to run a subprogram, you call the subprogram, or invoke it. Programming languages make a distinction between functions, which return a value to the calling program, and subroutines or procedures, which do not.

Most programming languages have bundled or included subprograms or functions that allow you to do certain kinds of work (like count the number of characters in a string, open files, and so on).

Define a Function

For this example function, suppose you have a program that frequently needs the average of three numbers. You can write a function that takes three numbers and returns the average. In most languages, you would then call this function by saying something similar to:

avg = average3(var1, var2, var3)

This tells the computer to execute the instructions in the average3 function with the values in the variables var1 , var2 , and var3 as input and store the resulting value in the variable called avg .

Now to tell the computer what the average3 function is. You do that by defining the function. In the function definition, you tell the computer what type of value the function is going to return, what information you have to give the function (in this case, the three numbers), and what the function should do.

In pseudocode, this average3 function definition looks similar to the following:

real function average3(real number1, real number2, 
            real number3)
  average3 = (number1 + number2 + number3) / 3
end function

In the previous pseudocode, you define the function by stating what type of value it returns and what types of values it needs to be given when you call it. In this case, you told the computer you were defining a function called average3 that would require three real values and would return a real value. The function adds the three numbers together, divides by 3, and assigns the result to a variable that has the same name as the function.

This convention of designating the value returned with a variable that has the function's name is used in QBasic and related languages. In other languages such as Java, a return command is used in code that looks similar to the following:

return (number1 + number2 + number3 ) / 3 ;

The values (variables) that you give any type of subprogram when you call it have a special name called parameters . In the previous example, number1 , number2 , and number3 are the parameters.

Define Subroutines

Subroutines are called similar to functions, but your program does'nt have to catch a returned value. Subroutines are often used to perform operations such as writing text to the screen or to a file.

The following is an example of a subroutine that calculates an age and prints it.

subroutine show_age(integer current_year, 
          integer year_born)
  integer new_age;
  new_age = current_year - year_born
  print "Your age is:" new_age
end subroutine show_age

You call your subroutine and give it the current year and the year in which someone was born. It does the subtraction and prints the value to the screen. Note that the variable new_age that is defined and used inside the subroutine can only be used inside show_age . It's called a local variable.

Some languages make no distinction between subroutines and functions. In JavaScript, for example, you can define a function as having a returned value or having no returned value.

2. CALL FUNCTIONS AND SUBROUTINES

After you write your subprogram, you need to call (or run) it from within your larger programs. Most programming languages use a syntax similar to the following for calling functions. To call your average3 function you wrote earlier, you'd write an instruction such as:

the_avg = average3(31.5, 29.8, 22.7)

In this example, you provided the three numbers to be averaged as literal numbers in the call statement. Alternatively, you could provide variables by name or a mix of variables and literal numbers. For example, to call the show_age subroutine, you could write something similar to:

call show_age( this_year, 1972)

Some programming languages require the use of a special instruction (such as call ) to run a subroutine; other languages let you simply state the name of the subroutine as an instruction. Fortran is an example of a language that requires a call statement; C/C++ does not.

A call to a function or subroutine can be embedded in another function or subroutine. In fact, this happens all the time, even in simple programs. Putting together complex computation by combining simpler parts in the form of subprograms is essential to programming.

Subprograms with Complex Variables

Recall from Lesson 2 that you can have a variable that contains other variables. Arrays are a common example used with subprograms, both as input parameters and as returned values. For example, you might write a subroutine to find the largest number in an array of numbers, or the longest string in an array of strings. The definition of the subroutine would simply state that it takes the name of an array variable as a parameter.

When to Write Subprograms

When you get rolling on writing a program, it's easy to find yourself with a single chunk of code that just goes on and on for pages and pages instead of breaking up the job into easily understood subprograms. You may think you're in control and can remember what all the bits in that great monolithic block of code do, but it's certain you'll find it easier to understand and maintain if you use subprograms. I once had to maintain a Fortran program (that somebody else wrote) that had 4,000 lines of code in a single chunk -- what a nightmare!

If you find your code getting longer than a page or so, start looking for opportunities to break it up

A Comment about Comments

This is a good time to talk about a good programming practice -- commenting your code. All programming languages provide a syntax for putting notes in your program that the computer just skips over. This is usually done by a special character sequence. In this example using the C convention, the computer ignores all text after the double slash:

// in C any text following // is a comment

Other languages, like Perl and UNIX shell, use the hash character for a comment:

# a comment in Perl or UNIX shell

And Visual Basic uses an apostrophe:

` a comment in Visual Basic

In some languages, if you have a lot of comments that need to stay together, you can place them between special character sequences:

/* 
    In many languages, you can place comments
    between special character sequences
*/

One of the marks of a good programmer is providing clear comments.

3. USE INPUT AND OUTPUT

Previous lessons have glossed over something important -- how to get information into a program, and how to get the results out. This area of programming is called IO (Input/Output). In the previous example, you used a simple statement called print to tell the computer to print text to the screen.

As with any statement, different languages have a different name for the print statement, so don't be surprised when you see another name for it later.

There's an obvious counterpart to the print statement, which is the input statement (also known by other names such as read in other languages). You use this statement to tell the computer to get some data from the user. For example, to ask the user's age, you might say:

print "How old are you?"
input (age)

In this case, you tell the computer to print the message, "How old are you?" and then read in something the user types, which you store in a variable called age . The convention for an input command is to accept characters from the keyboard until the Enter key is pressed, at which point all of the accumulated characters are interpreted as the age variable.

To see subprograms, input, and output at work, write a simple program in pseudocode that uses the average3 function along with some user input and output. It'll ask the user for three numbers, calculate the average, and print it.

real function average3 (real number1, real number2,
            real number3)
  average3 = (number1 + number2 + number3) / 3
end function
program do_average
  print "This program will ask for three numbers,
      and calculate the average."
  print "Enter the first number:"
  input (number1)
  print "Enter the second number:"
  input (number2)
  print "Enter the third number:"
  input (number3)
  the_avg = average3(number1, number2, number3)
  print "The average is :", the_avg
end program

In a real language, there would be statements to declare your variables, but I am skipping that detail in this pseudoprogram, for simplicity's sake.

When you run the program, it prints the first messages asking you for a number. When you type in a number, it stores that number as number1 . It then asks in sequence for two more numbers, and stores them as number2 and number3 .

The program then calls the function average3, passing it the parameters stored in number1 , number2 , and number3 . Because average3 is a function, it returns a value that you store in another variable called the_avg . You could state the effect of the function call as, "set the variable the_avg equal to the value the function average3 returns when given number1 , number2 , and number3" . Finally, the program prints the value of the variable the_avg and ends.

Other Kinds of Input and Output

Naturally there are other kinds of input and output besides printing to the screen and accepting keyboard input. For example, you can write a program that reads a mailing list from a file and prints Christmas card envelopes on a printer; however, all forms of input and output have universal requirements. Your program must describe output in terms of where it is going and exactly what data is to be output. Code describing input must state where it is coming from and the variables where the input is to be stored.

Twenty years ago, a discussion of input and output would have stopped here. But modern programmers have to deal with GUIs (graphic user interfaces) as found in Web browsers and the Windows operating system.

4. GRAPHIC USER INTERFACES AND INPUT EVENTS

As you sit at your computer screen using the graphic interface of a Web browser, your computer may have many processes going on. In addition to keeping track of your input by keypress or mouse movements, your computer may be sending or receiving data over a network and running other programs.

Fortunately as a programmer, you don't have to worry about these details because the operating system simplifies everything by means of a concept called event oriented programming . The operating system interprets the hardware actions of moving a mouse or pressing a key as events that are passed to your program. For example, if your program has executed the following statements:

print "Enter the first number:"
input (number1)

the operating system hands your program events that contain the characters that are typed on the keyboard, and your program interprets these events according to the input statement rules.

Moving a mouse around generates a huge number of events; every time the mouse pointer points to a new screen location, it may be significant to the program that controls that part of the screen. You have probably seen this in action on Web pages where a slight movement of the mouse causes an image to change.

The following are some examples of mouse events your program might receive. In every case, the event contains information on exactly where it happened.

  • Mouse has entered your working area
  • Mouse has moved with no button pressed
  • Mouse has moved with a button pressed
  • Mouse has left your working area

A Familiar Example of a Mouse Event

Imagine you're browsing a Web page. You move your mouse over an image and it changes. What happened is the Web browser got a mouse event and called a function written in a scripting language. In addition to controlling the way a Web page looks, the conventions of HTML (Hypertext Markup Language) allow for attaching a JavaScript function to the page so that it can respond to events.

If you haven't worked much with HTML, don't worry about the following examples. HTML is secondary to the discussion about events. Lesson 5 includes a bit of an introduction to HTML and other markup languages.

You can define properties for certain HTML tags, such as the tags that include images in a page, to provide instructions to the browser on what to do when the mouse is moved over or away from that image.

Here you have a basic HTML tag for adding an image to a page. It states that the image is to be taken from a particular file.

<img src="picture.jpg">

You can add extra information to this tag, giving the image a name and attaching calls to functions written in JavaScript, resulting in something similar to the following:

<img src="picture.jpg" name="SwapImage"
onMouseOver="functionA(SwapImage)"
onMouseOut="functionB(SwapImage)">

You provide a name for this image ( SwapImage ), and then give a function call for two events , onMouseOver and onMouseOut. The first event occurs when your mouse pointer moves into the image area; the second occurs when you move the mouse out again. When the event occurs, the corresponding function is called.

5. A FUN EXAMPLE

Now for an example that's not only fun, but also demonstrates many of the programming concepts you have learned in the last three lessons. The programming language is JavaScript embedded in a Web page. When JavaScript appears in a Web page, there's no main program; the real main program is the browser, and JavaScript provides added functions that are called by the browser when events occur.

In the following example, the HTML tags create a page that has a title, a line of text and an input form. After presenting the entire code, each part is discussed in detail. If you want to copy the following and play with it, be sure to save it as plain text (not a word processor format) in a file named Example.html.

<html>
<head><title>Example with Input and Events</title>
<script language="javascript" type="text/javascript">
function doReverse() {
  var s = ctrl.msg.value ; // get input
  ctrl.msg.value = "" ; // erase input field
  for( i = s.length - 1 ; i >= 0 ; i-- ){
    ctrl.msg.value += s.charAt( i );
  }
}
</script>
</head>
<body>
<p>Type something then press Reverse
<form name="ctrl">
<input name="msg" type="text" size="40" value="" />
<input name="doit" type="button"
    onclick="doReverse();" value="Reverse" />
</form>
</p>
</body>
</html>

The first two lines tell the browser how to show the title of the page. The tag that starts <script tells the browser that one or more JavaScript functions are going to be defined in the text that ends with </script> so it does not try to display that text. The text in the area between the <body> tag and the </body> tag is what the browser uses to create the page display.

The page has a short bit of text followed by a form, where the form consists of a single text input field and a button. Figure 3-1 shows the display with some text typed into the form.

Figure 3-1: The Web page display with text typed into the form.
Figure 3-1: The Web page display with text typed into the form.

View a larger version of this image.

Note that the form is named ctrl ; the text input field is named msg ; and the button is named doit . These names identify those tags such as variables as far as JavaScript is concerned. In the tag that creates the button, the code that says:

onclick="doReverse();"

tells the browser to execute the doReverse function when it gets a mouse click on the button. When you type into the text field named msg , the keypress events sent by the operating system to the browser are interpreted as characters and are added to the field and displayed.

How the doReverse Function Works

The definition of the doReverse function is enclosed in curly braces, following the C convention. The next lesson discusses the conventions found in C family languages. For now, however, concentrate on how this function works.

The first line of the function is:

var s = ctrl.msg.value ; // get input

which illustrates a number of things you have already learned. The form named ctrl is an example of a complex variable made up of simpler parts. To get the text from the text input box, you have to address the individual parts using the names established in the form. The following shows how you could describe the way this line of code works:

  1. Get the variable named ctrl from the page.
  2. Get the variable named msg from ctrl .
  3. Get the contents of the msg variable by looking inside of value .
  4. Put the contents of that variable in the local variable named s .

JavaScript does not require you to declare the variable s as being of any particular type. Instead, it automatically adapts the variable to the type of value being stored in it. This characteristic is true of many scripting languages and is called weak typing.

Next there's a statement that puts an empty string in value . Following that, you have the code that puts the characters back into the form in reverse order. Remember what you learned in Lesson 2 about arrays having the first item at position zero? Well, strings in JavaScript are the same way. To get the last character in the string, you have to use an index equal to the length of the string minus one. The statement that controls the FOR loop says:

  for( i = s.length - 1 ; i >= 0 ; i-- ){

In plain language you would say, "starting with an index that points to the last character in the string s, subtract one every time through the loop, as long as the index is zero or positive."

The next statement:

  ctrl.msg.value += s.charAt( i );

says, "add the character in the i'th position in the string and to those already in the value variable. On every cycle, the FOR loop uses the next smaller index to work backwards through the string." The browser displays the changed content of the variable, and you end up with the text field filled with the reversed string, as shown in Figure 3-2.

Figure 3-2: The page as it appears after pressing the Reverse button.
Figure 3-2: The page as it appears after pressing the Reverse button.

View a larger version of this image.

Moving On

Wow, you got a lot done in this lesson. You were introduced to the important programming concept of subprograms, and how they're used. You saw some typical uses of input and output programming commands, and you got a quick introduction to how modern GUI programming uses events for user input in JavaScript.

The next lesson looks at some more traditional programming languages, and shows you what it takes to create a complete program in one of those languages. Before you move on, be sure to complete the assignment and quiz for this lesson. And don't forget to drop by the Message Board to see what your fellow students have to say.