development environment -...

26
Chapter 3: Extending the basic language This chapter will focus on the mechanisms used in all computer languages to extend the language beyond what is possible with the basic statements and expressions. This is done through providing built-in procedures and ways for programmers to define their own procedures. There are variations in the details of the mechanisms and the terminology. Because this is the most important concept in programming, other chapters will include discussion on this topic as well. After studying this chapter, you will understand what is meant by function and procedure understand what is meant by programmer defined procedure or function understand the distinction between defining a procedure and invoking a procedure acquire experience using built-in facilities and defining your own functions using HTML and JavaScript Motivating Example The examples for the chapter show a web page that changes depending on different conditions. Figure 1 shows a Web page with one line of text against one background. Note that HTML tiles the image specified in the background attribute to fill the screen. 1

Upload: others

Post on 18-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

Chapter 3: Extending the basic language

This chapter will focus on the mechanisms used in all computer languages to extend the language beyond what is possible with the basic statements and expressions. This is done through providing built-in procedures and ways for programmers to define their own procedures. There are variations in the details of the mechanisms and the terminology. Because this is the most important concept in programming, other chapters will include discussion on this topic as well. After studying this chapter, you will

understand what is meant by function and procedure understand what is meant by programmer defined procedure or function understand the distinction between defining a procedure and invoking a procedure acquire experience using built-in facilities and defining your own functions using

HTML and JavaScript

Motivating ExampleThe examples for the chapter show a web page that changes depending on different conditions.

Figure 1 shows a Web page with one line of text against one background. Note that HTML tiles the image specified in the background attribute to fill the screen.

Figure 1. Web page with bird background.

Figure 2 shows another version of the same Web page. This one has a different background.

1

Page 2: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

Figure 2. Web page with frog background.

In one implementation, this application is constructed so that each time the document is invoked by the browser, the background is determined by a pseudo-random procedure. In a variation of this application, the internal clock is consulted and if it is midnight to noon, one background is chosen; otherwise, the other background is displayed.

The critical features required by these examples include

a way to simulate randomness such as would be achieved by flipping a coin or rolling dice so that something can occur without any obvious pattern

access to the time-of-day

Introduction to conceptsThough examples of built-in procedures have slipped into the earlier sample applications, the official topics have included only assignment statements with operators such as addition and multiplication and combination statements such as conditionals and looping. In a theoretical sense, this is practically all you need. (The hedging here is because building the human-computer interface (HCI) and providing the pseudo-random feature found in many games are tasks requiring additional facilities beyond basic calculations.) However, all computer languages provide ways for the programmers to incorporate such things as common mathematical functions in expressions without the effort of writing out all the steps. The developers of different programming languages would not find any customers if it were necessary to re-code these common procedures.

Procedures such as common mathematical functions typically take inputs, called arguments, and produce results, the returned values. For example, the "square of a number" is a function for which the argument is the given number (say, 3) and the returned value is its square (in this case, 9). Some procedures are not like mathematical functions and perform some action without returning any result. For example, a procedure in a game may fire a (virtual) cannonball into the air. Certain languages

2

Page 3: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

distinguish in terminology and syntax between procedures that return results and ones that do not. JavaScript and ActionScript do not.

Computer languages typically provide other facilities in addition to mathematical functions, for example, implementing interface functions, control of special devices, interactions with the operating systems and other programs, or simply implementing code that have proven useful in the past. One relatively new notion is that since development of software is so difficult, programmers should re-use proven code as opposed to re-inventing everything themselves for each new project. This is a change from the early days in which each programmer essentially did everything to build each new application.

HISTORICAL NOTE: After establishing a systematic mechanism for enhancing the language to make a more comprehensive, usable product, the developers realized that programmers also may want to add to the base language. This motivated the development of programmer-defined procedures: give programmers a way to define sets of statements, give each set a name, and specify where the named set of statements are to be invoked in a program. (Note: sometimes these are called user-defined procedures, but that phrase can be confusing since it is not the end-user of the finished application, but the creator of the application that is the user in this situation.)

The mechanism to define new procedures helps teams of people share programs or parts of programs. For example, it can be useful to share and re-use sets of values or ways that programs may interact. Building an application is best done by dividing the project into parts. Defining procedures or functions is a part of this.

Description: procedures, functions, methods

The formal way that these additions are provided varies across the different languages. For example, some programming languages provide global procedures that can be used anywhere. In Chapter 1, you read about two Flash global procedures: stop and goToAndPlay that each affect the flow of control from frame to frame.

Some languages support a construct called classes and objects in which data and code are tightly coupled. This subject will be expanded further in later chapters. Briefly, for now, classes hold the definition of data and procedures, called methods, for manipulating the data. Objects are instances of specific classes in the way in which whole numbers are instances of a data type called integer.

Certain methods are designated as class methods and are independent of any specific instance. The Math class and its class methods, for example,

Math.floor(value)

will be used in the sample applications in this chapter and several others. Some languages do everything with classes and objects, some use global procedures and some do both.

EXAMPLE: The application using random processing will use the built-in class method Math.random(). The application using the time-of-day will use the Date object and the getHours method.

Description: accessing built-in facilities

3

Page 4: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

Computer languages have built-in features including basic mathematical functions and other facilities. To indicate the variety but also the similarity in the features, here are some examples.

TECHNICAL NOTES: Some languages require programmers to take explicit steps to incorporate the built-in facilities needed, perhaps providing a way of specifying a list of libraries during the compilation step or a later linking step or adding special statements, called header or include statements, in the program itself to specify what is required. To put it another way, these things are part of the language and you can get them whenever you want, but you may need to specify what you need. A variation of this is that putting one special type of statement at the start of your code means that the references in the program can be relatively simple.

In Java, the start of a program file may include statements such asimport java.lang.*;

This tells the compiler (Java programs go through a translation process called compilation) that code in this file may make use of classes, methods and properties in the lang class of the java package using an abbreviated form of the name. For example, this means the code can use Math.PI instead of java.lang.Math.PI. It is possible to omit the import statement and use the long form.

Python, a language used by itself or as the scripting language in conjunction with other software, also has an import construct. The following two lines would appear in a Python script to indicate that this script made use of other scripts:

import Blenderfrom Blender import NMesh

These specific statements (with, perhaps, some others) are necessary to use Python with Blender, an Open Source 3D modeling tool. While the term is the same and one can say the final results are similar, the import statement in Python essentially brings in the full text of the original documents to be interpreted and executed on the spot. Generally, these are statements that define procedures and variables and do not have immediate consequences, but it may be necessary to be aware of the distinction between establishing ways of reference versus actual inclusion into the file.

The following is an example of what is required in C++.#include <iostream>using namespace std;

This brings in a small file, called a header file, so that the compiler can properly check and translate the use of certain input/output commands.

END OF TECHNICAL NOTES

JavaScript is a small enough language so that all the built-in facilities are available without any explicit action. The Application section in this chapter will show the way to include programmer code, perhaps your own code written previously, for use in a new

4

Page 5: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

document. The JavaScript mechanism is similar to Python: the old file is brought into the new document.

Assuming any necessary steps are done to signal that the needed built-in or previously developed features will be used, your code can make use of the features in the statements in your program. There are three main formats:

The built-in feature can be invoked using a procedure call. In Chapter 1, you sawgoToAndPlay(nextstep);

This is referred to as a procedure call. Something is done! Some languages call these procedures that do not produce and return values subroutines.

The built-in feature is a procedure that returns a value. As stated previously, the term 'function' is sometimes reserved for this situation, but this is not the case in JavaScript, where function means a procedure with or without a returned value. Two examples of this were shown in Chapter 2 in combination

dievalue = 1+ Math.floor(Math.random()*6);

and will be used in later chapters to 'throw dice'. Formally speaking, the Math.random is an example of a class method of the built-in Math object. What it does is produce a value between zero and 1 that changes every time it is called. The opening and closing parentheses following it indicate that it is a function, but has no parameters. The Math.floor is another class method of the Math object. It does have an argument. This Math method produces the largest integer not bigger than its argument. You may think of it as rounding down or truncating a number. The value of Math.floor(1.34518) would be 1.

The application in Chapter 2 made use of a method for string objects. The codetotals.substr(0,dp+3);

performed a calculation on the string held in the variable totals. The calculation was to extract a portion of the string based on the two arguments.

Built-in features can be provided using data associated with objects, also called properties or attributes. Objects will be discussed further in later chapters. For example, in JavaScript,

totals.length

yields the length of the string totals. It should be noted that some languages will provide the way to determine the number of characters in a string as a function with an argument and not as a method:

length(totals)

Another example of a property is the way JavaScript provides the value of pi, the mathematical constant the expresses the ratio of the circumference of any circle to its diameter:

5

Page 6: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

Math.PI

This is a class variable of the class Math. Again, later chapters will address objects and classes.

Description: programmer-defined procedures

Programming languages provide a way for you, the programmer, to make the same kinds of extensions to the base language as done by the developers of the language when constructing the built-in facilities. Assuming this is done, your code can contain calls to the procedures, functions, methods and properties. The 'assuming this is done' can be misleading. For example, if you decide to define a function that computes the value of a commission based on information on sales, you may work on the parts of the program that use this function before you actually write it. Two conditions must be met. The first is that eventually you do write the function definition or locate a copy of pre-existing code for the function definition. The second is that the language processor processes this definition before reaching the statements that make use of it. The function definition and the invocation of the function are distinct.

A programmer-defined procedure is a set of statements. These statements perform a well-defined task that has meaning for the programmer. The procedure can make use of arguments: extra information to customize the procedure for the specific situation. The mathematical functions sine and absolute value were cited earlier in this section. Some languages refer to the extra information as arguments in the calling of the procedure and parameters when in the procedure. In this text, we take a more informal approach.

The question for new programmers generally is why or when to define your own procedures, functions or classes. Unfortunately, the decision may not be clear cut. One reason is to avoid entering the same code two or more times. Another reason is to make the code easier to read. A related reason is to help in the creation process by dividing large tasks into smaller ones. If one program is very long, do look for ways to split it up into parts.

REAL-LIFE NOTES: Analogies can be made to every day life concerning the definition of procedures. When you offer to give directions to someone, say to an office on campus or to the library in a particular town, you may ask the person, "do you know how to get to …." and, if they do, give the directions from that point. Your complete directions are: go to X and then do these several things to get to the final destination. If you are sharing a cooking recipe, you make use of what the listener already knows. If they know how to make pasta, you say "make pasta" and do not talk about boiling water. This gives you the opportunity to spend most of the time on describing your great sauce! Continuing with the cooking pasta example, there is an analogy to arguments. You can say "make the pasta using linguini and make it 'al dente'. In this case, the procedure is make pasta and two arguments are the type of pasta and a phrase indicating how hard or soft to make the final product. Other function calls could be

make pasta linguini, softmake pasta orzo, softmake pasta spaghetti, al dente

6

Page 7: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

The person giving the orders and the person hearing and acting on them need to agree on what the parameters are, for example, what al dente means. This is directly analogous to the situation in programming in which the calling statement and the procedure as defined must agree on the use of any arguments.

END OF REAL-LIFE NOTES

TIP: Most programming languages provide ways to build programs that make use of other programs you have written as well as the built-in programs. The benefit of this approach is not evident if you and only you create one and only one program. However, if you are working on a project involving other programmers, you create your own programs and then do what has to be done to include or establish references to the other people's work. If you are making several programs, you will appreciate the value of producing code, testing and making sure it works, and then re-using it again and again.

Writing a program or procedure generally involves a format for the first or header line. This includes a specification of any inputs (arguments) required by the procedure. Some languages allow arguments to be optional, and, some of those provide a way to set a default value. The header line may indicate whether or not this is a procedure that returns a value so that it can be used in an expression. The format for procedure specifies some bracketing symbols or line indentation and formatting to demarcate the statements of the procedure.

EXAMPLE: The examples will make use of programmer-defined procedures to make the determination of the background for the web page.

Reading checks1. Describe what is meant by a procedure in programming languages.

2. Describe the way Java, Python or C indicate that certain built-in procedures are to be used in the application.

3. What is the value of Math.floor(X) when X holds the value 21.42? 5.003? .3333?

ApplicationIn this section, we first revisit the sample programs used in previous chapters using the terminology of procedures, functions, and methods. You will see modifications of the Coffee Shop application that demonstrate function, function calls and the use of external scripts. Then you will create a new Webpage in which the background changes either randomly or based on the time of day.

Review of previous examplesAs has been indicated, the Flash example in Chapter 1 made use of built-in procedures:

stop(); goToAndPlay(nextstep); goToAndPlay(1);

7

Page 8: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

These are global functions in Flash. They change the flow of control from frame to frame. The stop function does not take an argument; hence the empty parentheses. The goToAndPlay function does, namely the label for the frame that control is to go to in the Flash movie.

In Chapter 2, the Document Object Model defining the interplay between JavaScript coding and the HTML document was used to extract and modify what was on the screen. The onSubmit attribute value for the <form> element was set to

return addup();

where addup was a function defined in the <script> element in the <head> element. This statement performs two operations.

1. The addup function is invoked (execute) returning a value. If you recall, the value was the Boolean value false.

2. This value is returned to the browser program, which uses it to determine whether or not to reload the HTML document. Since the value is the value false, the document is NOT reloaded.

Examining the coding in the script element, you can see that the definition of addup begins with the function header line:

function addup() {

This line indicates a function definition, the name of the function, and the fact that this particular function does not use any arguments.

TECHNICAL NOTE: At this point, you should start to realize that a function name followed by opening and closing parentheses calls (invokes, executes, runs) the function in the scripting languages JavaScript and ActionScript. The parentheses are necessary to indicate that this is a function call. In a later chapter, you will see that the coding of the function name without the parentheses, as in

if (addup)

is a way to check if the function is defined.

The use of a function call in the assignment of attribute values is the typical way to implement buttons in HTML/JavaScript. The requirement for the language is any well-formed JavaScript expression. It is legal and possible to put all the code for the function in the <form> tag, but it is awkward to type and quite error-prone.

The function made use of the String method substr for extracting a portion of a string.

In the Coffee Shop application, it was necessary to change the string that was produced by the original calculation in order to be the standard format for dollars and cents. The coding to do this was done in the addup function. An alternative approach would be to define a function that would take the original string as the input argument and return a properly formatted string for dollars and cents. The coding would be the following, shown here in its entirety. The name of the function is money.

8

Page 9: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

function addup(f) {var total; var taxrate = .08 ; var drinkbase;opts=f.drink;drinkbase = f.drink[opts.selectedIndex].value;var sizefactor; var i; var totals; var dp;for (i=0;i<f.sizef.length;i++) {if (f.sizef[i].checked) { sizefactor = f.sizef[i].value; } }total = sizefactor * drinkbase;total = total*(1 + taxrate);f.label.value="Total with tax";f.totalf.value= money(total);return false;

}

function money(orig) {var formatteds; var dp;formatteds = orig + "00";dp = formatteds.indexOf(".");if (dp<0) {return ("$" + orig+".00");}else { return ("$" + formatteds.substr(0,dp+3)); }

}

This does exactly what the coding in Chapter 2 does. The statementf.totalf.value= money(total);

invokes the money function using the string in total as the argument. The original names, that is, total and totals could be used in the money function, but were changed to make it clear that the names inside the called function are distinct from the names outside. Whatever was the argument when money is called, that is, the value of the string total, becomes the value of orig in the function money when it is executed. The money function returns a new string, the formatted dollar and cents. This value becomes the value of the right hand side of the assignment statement and is assigned to f.totalf.value.

Why make the change (other than to illustrate a pedagogical point)? The answer is that you may need to format money in some other application. If you define a function that does the job, it will be easier to copy it to your new project. Alternatively, you can extract the money function from this file and make it its own file using a name such as

9

Page 10: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

money.js. In the coffee shop file, this can be done using attributes in the <script> tag:

<script language="JavaScript" type="text/javascript" src="money.js" />

This would be followed by a script element holding the addup function definition. That is, there are two script elements in the new HTML document. One holds an external reference and is a singleton tag. The other starts with a <script> tag, has code as contents and ends with a </script> tag.

TIP: The particular example of formatting money suggests another reason to separate this functionality from the rest of the application. Ignoring the issue that the text on the page is in English, this money function that formats for dollars-and-cents could be exchanged for one that does formatting for other currencies, such as euros or yen. See the exercises for a variation on this approach.

You may choose to put all the JavaScript coding in one or more external files and have no internal scripting.

Now it is time to go on to the implementation of the motivating examples for this chapter.

Description of applicationYou probably have visited a Web site with a changing background. The changes may be based on some condition or be totally random. The issue of randomness deserves attention. How, if everything is to be programmed and there are no little men with dice inside the computer, do you, the programmer, arrange for something to occur randomly? The answer is provided by built-in features available in most programming languages. They are called 'pseudo-random' because the way the language processor produces the random results is based on a fixed procedure. The developers of the language claim that the random facility produces numbers in a set range with equal probabilities and with no discernible pattern. The specific functions available for pseudo-random behavior do vary. Some produce integers within a specified range; others, such as that available in JavaScript, produce a number, a fraction, between zero and 1. With a value such as this and some mathematical manipulation, you can simulate random events.

Plan of attack The background of a Web page can be set by the background attribute in the <body> element. However, it is possible to change this in code using an assignment statement with the left hand side (the target) as follows:

document.body.background = …

The choice of what to assign will be made in the true and false clauses of an if statement. The condition for the if statement will involve a call to Math.random.

The code with the if statement will be defined in a function and the function will be defined in the <script> element in the <head> element the same way as the addup function was defined in the examples in Chapter 2. Now the question is where to put the call to the function? The solution is that the <body> tag allows an attribute named

10

Page 11: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

onload. Giving this attribute a value of a string representing JavaScript code indicates what is to be done when the document is first loaded or later refreshed (re-loaded).

An outline for this HMTL/JavaScript application is

html elementhead element

title elementscript element

definition of change functionif statement with assignments

body element with the start tag having an onload attribute settext

Use of concepts in implementation

To save space and force you, the reader, to build on your understanding, the code samples from now on may not be complete. The discussion may even go 'out-of-order' to reflect how a developer actually plans and puts together a program. Remember, no matter what development environment you are using, you do not have to write the code in order. Use the outline provided in the previous section to guide you on what goes where. In general, function definitions will go in the script element in the head element at the start of the html document. The body element will hold the visible material for the project.

For the application in which a different background is displayed depending on a calculation involving the pseudo-random facility, the <body> tag will have the addition of an onLoad attribute:

<body onload="randombackground();">

This coding 'tells' the browser to invoke the function indicated when the document is displayed the first time and any subsequent times, such as when the person at the computer clicks on the refresh icon.

The rest of the document can be anything you want. The screen shots showed here had<h1> This is text against some background. </h1>

and then the closing </body> tag. You could use the code in the Favorite Web site example from Chapter 1 or the examples from Chapter 2. Of course, there is an advantage to do something really simple since the focus here is on the manipulation of the background image.

Writing the body statement as shown assumes that there is a function defined called randombackground and that the function does not use any arguments as specified by the opening and closing parentheses with nothing in-between. You will write the code for this function in a script element in the head element at the start of the html document. The browser will have read in and stored the definition before getting to the

11

Page 12: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

</body> tag. The function will be defined and ready to use before the onload setting is made and then acted on to invoke (execute) the function.

The definition for the function starts with a line including the word function, the name invented for the function and then the opening and closing parentheses indicating no arguments.

function randombackground()

The word function is part of the JavaScript (and ActionScript) language. The function consists of one if statement with both true and false clauses. What follows are the statements that make up the function definition enclosed by curly brackets.

{if (Math.random()>=.5) {

document.body.background = "bird.gif";}else {

document.body.background = "frogface.gif";}}

The condition in the if statement is what the expression in-between the opening and closing parentheses is called. The code in the first set of brackets is the true clause, what happens when the condition Math.random()>=.5 is true. The code in the brackets after else is the false clause; it is executed if the condition is false.

This particular condition calls the built-in Math method that produces a random value. The value will be between zero and 1. To be accurate, the value can be zero but cannot be 1. You can think of it as a fraction. The expression compares this value with the value .5. This means that there is a 50-50 of the condition being true.

The JavaScript language processor supplies different values for Math.random() every time it is invoked. The developers of this system claim that every value is equally likely and there will be no discernible pattern.

Make sure the HTML document is complete and try this application out in the browser. You can use the refresh button or go to the File pull down menu and open the file again to see the changes. Keep in mind that the coding specifies behavior that appears random. Do not expect the two backgrounds to alternate back and forth, back and forth, or appear in any pattern. There may be runs of one background just as coin flipping can produce runs of heads or runs of tails.

The next application uses a different condition to make the choice between the two background settings. The general outline is the same. There is still a call to a function set up by the onload attribute in the <body> tag. Most programming languages provide a way to find the time. This is called the system or internal clock. JavaScript has what is called the Date object. The coding

var d = new Date();

12

Page 13: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

specifies that a new Date object is created. When called in this way with no arguments, an object is created that holds information about the date and the time. The var statement sets up a variable named d. The new keyword is used whenever a new object needs to be created. You will find out more about var and new in later chapters.

The next line shows an if statement.

if (d.getHours()<12) {

The condition d.getHours()<12

performs two steps. First, the getHours() method extracts from the Date object held in d, a value from 0 to 23. This is a representation of the hours in what is called military or 24-hour clock. The second step is to compare this number with 12. This condition will have the effect of displaying the first background from midnight to noon and the second background from noon to midnight. Let us be precise: the first background will be displayed up until, but not including, the noon hour. The second background will be displayed from noon to midnight, but not at midnight.

TIP: Now the question arises of how do you check this program? You can test it throughout the day, and if this was a serious application, you certainly should. However, before doing that, test it by changing the less than (<) to a greater than (>) sign and see if the other background appears.

Reading Checks1. Change the program to choose the display from 4 different choices making a

random choice. You can do this assigning the result of Math.random() to a variable, call it ch, and then using if statements to compare ch with .25, .5, and .75.

2. Change the program to choose the display from 4 different choices using the time of day. You will define the hours corresponding to night-time, morning, afternoon, and evening.

What can go wrongAs is always the case, syntactic errors will cause problems. The definition of the randombackground function ends with two closing curly brackets: one to end the else clause and the other to close the function itself.

TIP: If a function consists of just a single statement, you can omit the outer opening and closing curly brackets. Similarly, since the true clause and false (else) clause are each just one statement, you can omit those curly brackets as well. However, do not do this even if you see it in examples. This practice is just too error-prone. You may need to go back and put in another statement. For example, this was the case in changing the function to check the time.

A common mistake by new programmers is to code as they would talk, writing

13

Page 14: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

if (Math.random()>.5) {

}

else (Math.random()<.5) {

}

Do not insert a new condition after the word else! The underlined part is incorrect.

Spelling counts, but in a complex way. You do need to spell function correctly and not only must you spell Math.random() correctly, but you need to remember to capitalize the first letter of Math. However, you may call the function anything, say, randimbkgrond, as long as you do this consistently: in the onload setting and in the function definition.

The image files must be in the same folder as the HTML document. This means the same folder on your computer or the same folder on the server computer if you upload this application to be available on the Web. You need to get the right name and the correct extension. Asking for bird.jpg will not get bird.gif. If the image file is not actually the type of image file indicated by the file extension, it will not work.

Chapter summary and ReflectionThis chapter focused on what often is viewed as the most important idea in programming: the notion of a procedure. The procedures featured here included the built-in class methods of the Math class of JavaScript. Attention was paid to the general task of including built-in code in your application.

The issue of using code that is not your own may come up in your programming classes. In certain cases, the teacher may say, or, perhaps under questioning, admit, that there is a library or class with material that you could use. However, the teacher may say, "For this assignment, do it all yourself!" This is the teacher's prerogative. In other situations, the teacher may set you the task to do the research to find the procedures, functions, methods, properties, etc. that you will use to accomplish the task and then use them.

It is worth repeating that the concept of procedure or function is fundamental to programming. Beginners resist defining functions. Try to overcome this. When in doubt, make a function! It will facilitate the problem solving aspect of the work and this is generally the greater challenge than the coding and the typing.

HISTORICAL NOTE: The challenge of creating pseudo-random functions that are truly random is still an area of research in computer science. Every now and again a news story appears concerning a lottery or some other process that was supposed to be random and was not. Some times this involves the underlying function and sometimes in the use of the functions.

14

Page 15: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

If you were a programmer If you worked in an industrial setting, you will need to be aware of programs created by other people as well as the built-in facilities for the programming language in use. It could be that in your organization, many programs would have been developed to be used in new applications and when changing old applications. Finding how if there is a program to do something may get frustrating. However, the re-use of programs (software) will be encouraged and, often, will be required to get the job done.

The background images of an organization's Web site constitute an important part of the impression given by the institution. If you want a static background image, you use

<body background="bird.gif" >

The potential negative features of background images include

they may detract from the legibility of the text in the document,

they may distract from the graphics, specifically the graphics that has important content, such as product illustrations, and

an image file takes time to load.

An alternative to background is the attribute bgcolor, which can be set to specify a color using one of a set of pre-defined names (for example, "red", "blue") or RGB values. You can look these up in on-line tables or books or access them in graphic programs such as Adobe Photo Shop or Jasc Paint Shop Pro.

Testing programs involving random behavior or involving time-dependent behavior requires plans and patience. The changing background application based on pseudo-random calculations requires you to load and re-load the application several times. The application dependent on time of day requires careful re-setting of the conditional and then, to be fully convinced, waiting for both time periods to occur. Applications with these features, along with complex interactions with user interactions and other external events, are becoming more common so you need to appreciate the importance of this situation and learn ways to accomplish the testing. Later examples in this text will provide you more practice at this task. A big part of testing, after you have completed your own tests, is to recruit users and observe the results when someone other than you, the application builder, uses your program.

What's next The next chapters will elaborate on the basic features of programming languages, including providing full explanations of some of the coding you have already used: events, variables and functions.

Exercises 1. What is the difference between function definition and function execution?

2. List all the programmer-defined functions in the sample applications shown in chapters 1, 2 and 3.

3. List all the built-in procedures and methods used in the sample applications shown in chapters 1, 2 and 3.

15

Page 16: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

4. How is a function defined in HTML and JavaScript?

5. What is the correct way to include the coding in a file called scores.js in a new HTML document?a. import scores.jsb. include scores.jsc. <script language="JavaScript" type="text/javascript" src="scores.js" />d. <include file="scores.js" />

6. What is the correct first line of a function definition for a function named addtip that takes one input argument called bill? (This is before the statements surrounded by curly brackets.)a. addtip for billb. function addtip(bill);c. function addtip(bill)d. addtip = new function (bill);

7. What is the correct way to invoke the addtip function just described? Assume that total is a variable that holds the amount of the bill. The result will be placed in document.f.final.src.a. document.f.final.src = call addtip with total;b. document.f.final.src = function (addtip, bill);c. document.f.final.src = addtip(bill);d. document.f.final.src = addtip(total);

8. If it is 3 o'clock in the afternoon, would the example shown here show birds or frogs?

9. Check if the money function works with values below 1. You will need to change the price information in the options and radio buttons. Modify the application to round to the nearest nickel. Should this be done in the money function or in the calling program? There are arguments for either way.

Projects10. Improve the money function to work for dollar amounts up to 100,000, that is, do

the manipulations to put in commas appropriately.

11. Choose a currency other than US and write the money function.

12. Combining your results from the previous exercise, write a new money function with two arguments, the string to be reformatted and the type of currency. A call would be: … money(total, "euro"); or money(total, "US");

13. Do research on-line to find the other properties and methods of JavaScript Date objects. Look up how to use document.write() and add a date, in different formats, to the top of a Web page.

14. Take what you have learned in chapter 3 for changing the background of an HTML document and apply it to the Web page you created in chapter 1.

16

Page 17: Development environment - faculty.purchase.edufaculty.purchase.edu/jeanine.meyer/programminglogicboo…  · Web viewThis chapter will focus on the mechanisms used in all computer

For teachers only: Tips for TeachersFunctions are an important concept in programming and so I chose to introduce them early, informally in the first and second chapters and then more formally in this chapter. Functions, variables and parameters also will be the focus of chapter 6 and used in every chapter in the text. I do try to present the reasoning behind making a function definition since that is an issue for most students.

Depending on the sequence of courses and languages in your institution, you may choose to show students syntax from other languages for various features.

A benefit of the HTML and JavaScript environment is the way that function calls can appear in onSubmit and onLoad (and later href) attributes and function definitions reside in the script elements. This encourages students to view defining functions as the natural thing to do. This would not be the case in a programming environment that could be one long program.

The distinction between defining the function and calling the function is an important one. One error that produces a teachable moment is if a student writes something like:

addup(); … function addup() { …}

That is, calls the function in code in the script element before the function is defined. This allows you to point out that the definition had not been processed.

A later chapter will use the JavaScript idiom of making function names by themselves indicate if the function exists or not to manage browser differences. It is a good time to reinforce why the parentheses are needed.

The issue of appropriate re-use versus cheating can be a challenge. My strategy has been to say that the students can learn from anyone, but when they bring programs to class to demonstrate, they must understand everything and be able to explain all the code. Generally, I have had the luxury of being able to sit with each student as they demonstrate the work. A benefit of using games and similar applications for assignments is that many students will make the effort to learn about features not explained in class.

17