## Lesson 1: Algorithms and JavaScript

Due by the beginning of class on Monday, Jan. 25

Before you begin learning how to program, it is important to note that the process of programming has been around since long before the advent of computers. Underlying programming is the design and implementation of algorithms. An algorithm is a clear, step-by-step sequence of instructions for performing some task.

Whether you recognize them or not, you are confronted with algorithms every day. When you shower in the morning, an algorithm for shampooing your hair is printed right on the bottle:

1. Wet hair and lather.
2. Rinse thoroughly.
3. Repeat if necessary.
When you microwave a frozen dinner, an algorithm for proper cooking is printed on the box:
1. Pull back lid at corner of box to vent. Do not fully remove lid.
2. Heat on HIGH for 4-5 minutes or until hot.
3. Let stand covered for 1 minute.
4. Carefully remove lid as product will be hot.
5. Stir product.
Both of these algorithms specify a sequence of actions to be taken in order to achieve a particular goal. In the first, the goal is clean, shiny hair. In the second, it is hot, edible macaroni and cheese. By following the steps prescribed in these algorithms, a person could presumably achieve these goals.

Exercise 1:     Specify an algorithm for identifying the oldest person in a room full of people. That is, give a sequence of simple instructions that a person could follow to identify the oldest person in a room. Note that appearances can be deceiving, so don't rely on instructions such as "look for the person with the most gray in their hair." You may assume that if you ask a person their age, they will tell you accurately.

Exercise 2:     Suppose you have two glasses, a red glass containing Root Beer and a blue glass containing Mountain Dew. Specify an algorithm for swapping the contents of the two glasses. That is, when done executing your instructions, the red glass should contain Mountain Dew while the blue glass should contain Root Beer. You may assume the existence of an additional white glass if you wish.

### Algorithm Clarity?

A key component in the concept of an algorithm is the person or entity that is to carry out the prescribed steps. Similar to the old adage about "a tree falling in the woods", an algorithm is meaningless without someone or something to execute it. And in order for the algorithm to be well-defined, its steps must be clear and unambiguous to that intended executor. Look again at the algorithm for shampooing your hair. Do you find each of the steps to be clear? Chances are, the typical adult would have no problem understanding what "rinse thoroughly" and "repeat if necessary" mean. With a lifetime of experience washing their hair, these phrases have a common sense meaning. Thus, this may be viewed as a well-defined algorithm for the typical adult.

Now consider the shampooing algorithm from the perspective of a small child. Would a child who had never washed their own hair be able to tell the difference between thorough and non-thorough rinsing? Would they be able to determine whether repetition were necessary? Probably not. For that executor, then, this is not a well defined algorithm. To a small child, the individual steps are to vague to describe a precise sequence of actions.

Exercise 3:     Specify an algorithm for traveling from your dorm room to the computer lab in South College. Assume that the person who will follow your instructions is a typical Dickinson freshman, with knowledge of the general layout of the campus and the location of landmark buildings such as Old West and the HUB.

Exercise 4:     Now specify an algorithm for traveling from your dorm room to the computer lab, with the intended audience being someone completely unfamiliar with Dickinson. Note the level of detail required here as opposed to in the previous exercise.

### From English to JavaScript

The above exercises were designed to pound home the point that algorithms are defined with specific executor in mind. When you supplied directions in Exercise 3, you were able to rely on the background knowledge of the student following those directions. In contrast to the directions from Exercise 4, this made for shorter, more high-level instructions. Without a familiarity with the campus, the directions had to be more detailed and low-level.

Describing algorithms in a spoken language such as English (or French, Spanish, German, ...) certainly opens up possibilities for misunderstandings. Different people may read the same sentence and yet have different interpretations of its meaning. Phrases such as "the ugly building" and "take a hard left" have very subjective meanings. Fortunately, spoken languages are rich enough and usually contain enough redundancy to avoid such problems. Still, who among us has not gotten lost after faithfully following someone's directions?

All of this talk of algorithms has finally gotten us back to the topic of programming. Programming is really nothing more than designing algorithms with a specific executor in mind: the computer. When you write a program, you are specifying a sequence of instructions that you want the computer to execute. And since computers are literal-minded, doing exactly what you tell them to do, there is a premium on clarity when programming. As such, complex, inherently ambiguous languages such as English are not well-suited for communicating with computers. Instead, we specify instructions in simpler, more precise programming languages such as JavaScript.

Consider the task of averaging a list of numbers. An English description of an algorithm might be as follows:

1. Obtain the list of numbers.
2. Add up all of the numbers in the list by adding each number to a running sum.
3. Divide the sum by the number of values in the list.
4. Display the average.

While this algorithm is perfectly clear to a human being, it is far too vague in places for a computer to execute. This same algorithm, coded in JavaScript, is listed below.

list = [92, 84, 70, 95]; sum = 0; for (i = 0; i < list.length; i++) { sum = sum + list[i]; } average = sum / list.length; document.write("The average is " + average);

Since you have yet to begin learning the JavaScript language, you are not expected to understand the details of this code. However, it is not difficult to surmise that each section of code corresponds to a step in the algorithms as stated above. The first line gives a name, list, to a list of numbers. The next section of code adds up the numbers in the list under the name sum. Next, that sum is divided by the number of items in the list, yielding the average of the numbers. The last line of code finally displays the average.

For the first part of this course, you will be executing JavaScript code such as this in a simple interpreter window. This window can be opened by clicking on the "JavaScript Interpreter" link that appears to the left of this page. (If the red stripe containing class links is not currently on the screen, you can click on this link to open the window.)

The interpreter window contains a box where you can type in JavaScript code, and then click on the button to execute that code. Using the mouse, you will be able to cut-and-paste code back and forth from the interpreter and the lessons. In case you have not had much experience with windows, to cut-and-paste text from one window to another:

1. Highlight the desired text by placing the mouse at the beginning, holding down the (left) button and dragging the mouse to the end of the text, and then releasing the button.
2. Make an internal copy of the highlighted text by selecting "Copy" from the Edit menu at the top of the browser window.
3. Copy the text by clicking the mouse at the desired location and selecting "Paste" from the Edit menu.

Exercise 5:     Cut-and-paste the averaging code from above into the interpreter and execute it. Report the output.

Exercise 6:     One nice feature of the JavaScript interpreter is that code can be edited and re-executed in order to perform different computations. Edit the code by adding the number 100 at the end of the list, preceded by a comma to separate it from the previous number. Then execute this modified code to obtain the average of these five numbers. Report the output.

### Syntax Errors

For the most part, human beings are able to look past typographical or grammatical errors in language and discern the desired meaning. Computers, on the other hand, are completely inflexible with respect to errors. Even the slightest variation from the specified form will cause execution to be halted. For example, if you forgot the closing right parenthesis in line 4 of the code above, execution would fail and a window would appear with the following error message:

JavaScript Error: http://www.dickinson.edu/~braught/courses/cs131s99/InterpInput.html, line 5: missing ) after for-loop control. for (i = 0; i < list.length; i = i + 1 { .......................................^

Typographical errors such as this are known in computer terms as syntax errors since they are violations of the strict syntax of the language, i.e., the rules which specify the form of statements. In order to assist you in fixing syntax errors, error messages attempt to identify the cause and location of each error. In this case, the error message specifies that there is a missing right parenthesis and points to the location where it should be placed. Note that a line number for the error is also specified, although the line number reported is always one too large (this is due to technical reasons that we will not discuss).

Exercise 7:     Simulate a syntax error by misspelling one of the words in the program. For example, in line 8 (starting with average), change the spelling of "sum" to "some". What is the result? Is the error message useful in locating the actual error?

### Lesson Summary

• An algorithm is a clear, step-by-step sequence of instructions for performing some task.
• In order for an algorithm to be well-defined, its steps must be clear and unambiguous to its intended executor.
• Programming is the process of designing algorithms whose intended executor is the computer.
• While spoken languages such as English and Spanish are rich and flexible, computers require more restricted and unambiguous programming languages such as JavaScript.
• The syntax of a language is the set of rules which specify how expressions in that language are to be formed. As such, typographical errors which violate these rules are known as syntax errors.
• Even the simplest syntax errors in a JavaScript program can cause execution to fail. Fortunately, the JavaScript interpreter displays error messages which help to identify errors in the code.

Solutions to odd numbered exercises (posted late afternoon of due date).