Development environment
Chapter 2: Basics
This chapter will focus on the basics in any computer language, namely statements, expressions and communication with the end-user. After studying this chapter, you will
• understand what is meant by a statement in scripting and programming languages
• understand several statement types common to most computer languages
• learn how what is termed an expression performs an arithmetic or logical calculation
• acquire experience using statements, expressions and simple input/output operations using HTML and JavaScript
Motivating Examples
To demonstrate basic concepts, we use two examples. Using HyperText Markup Language (HTML) and JavaScript, you will create two simple applications requiring user input.
The first example turns the computer into an adding machine. Do not be concerned: the examples will get more interesting. Figure 1 shows the initial screen.
[pic]
Figure 1. Simple calculator display
After the user enters numbers into the first three boxes and clicks on the add up button, the screen will resemble Figure 2.
[pic]
Figure 2. Calculator showing sum.
The second example is a specialized calculator for orders at a coffee shop. This example demonstrates use of dropdown menu and radio buttons.
REAL-LIFE NOTES: In the early days, many radios featured buttons instead of or in addition to dials. Only one button could be depressed at a time. If you pressed a second button, the first one would pop up. Most car radios have the mechanism to set a small set of buttons to your favorite stations. The computer interface analog is a set of buttons that allow only one button to be selected at a time. The selection is done using the mouse.
Figure 3 shows the initial screen.
[pic]
Figure 3. Coffee shop form.
Figure 4 shows the look of the screen after the customer has clicked on the downward arrow to reveal the dropdown menu and then selected Hot Cocoa.
[pic]
Figure 4. Pulldown menu with selection.
The next step is to select a size. The choices of size are implemented using a radio button group. This means that only one button can be selected. If and when a second one is clicked, the first button changes to the unselected state. Figure 5 shows the screen after a size has been chosen and the Order button pressed. The text fields reveal the total amount charged.
[pic]
Figure 5. After Order button clicked.
The critical features required for these applications include
• ways for the user to enter information (input) and
• ways for the application to display information back to the user (output)
• mechanisms for storing information such as prices
• mechanisms for calculations
• mechanisms for examining strings to format dollars-and-cents in the standard way
Introduction to concepts
Programming or scripting languages are defined by grammars, sets of rules, and made up of statements in the same way that formal written language is made up of sentences. The adjective 'formal' is important here. The principle difference between programming languages and natural languages such as English is that programming languages must be grammatically correct to work all. In contrast, you can understand other people even if they are not speaking correctly. It even is possible to understand people who make up words and idioms. You do not have that luxury when you are programming.
The underlying programming system translates correctly formed source code into machine code that the computer circuitry can run. If the source code is not correctly formed, in some cases (for example, ActionScript and Java), no translation takes place. In other cases, notably HTML, something will appear, but it may be very different from the programmer’s intention. The translation and execution process may be all at once or may involve multiple steps.
Continuing the analogy with natural languages, natural languages are made up of sentences and sentences come in different types, such as declarations and questions. Sentences are themselves strings of letters, blanks and symbols such as periods and question marks.
Programming languages generally have several different types of statements. Some statement types are called compound statements because they contain or can contain multiple statements. Statements are themselves made up of characters and symbols. For example, in several languages statements are ended with a semicolon and compound statements involve the use of brackets. In the next section, you will read about assignment statements and two types of compound statements, common to many languages.
Computer programs often require interactions with someone. This someone is termed the user or end-user, though a first step in good design is to identify these people with an appropriate name. For the second example in this chapter, the term customer will be used. In chapters in which the examples are games, you are targeting a player. The interaction of a person with a computer is called input/output (I/O) or human/computer interaction (HCI). The devices demonstrated in this chapter are pull-down lists, radio-buttons, and text fields. Later chapters will demonstrate other methods.
EXAMPLE: The adding three numbers application required the user to enter three numbers and then click a button. The application performed the addition and then displayed the result. The coffee shop application presented the customer with pull-down lists displaying the types of drinks and buttons indicating the sizes. The application calculated the price and displayed a formatted result.
In teaching programming, it is difficult to introduce some concepts without assuming or mentioning others. This chapter will touch on a few topics, for example, variables and arrays, which will receive more attention later. You will see the concepts in use right away in order to demonstrate other concepts.
Description: statements
Computer languages each come with several different types of statements. Common ones include
• assignment statements
• function or method calls
• conditional statements, specifically, the if statement
• looping statements, specifically, the for statement
An assignment statement sets or assigns a value, perhaps a calculated value to a place in memory. The term for the calculation is expression, which is to be covered soon. More abstractly, the assignment statement associates a value with a name.
The Flash example in Chapter 1 demonstrated the use of an assignment statement. Recall
nextstep = "diagonal";
This statement, when executed, made the variable nextstep have the value the string of characters "diagonal". (From now on, we will use the term 'string' to refer to a character string.) The semicolon at the end indicates the end of the statement. Many programming languages use the semicolon. Some use a line break to indicate the end of a statement. Some use both: that is, you can combine statements in one line by separating them by semicolons.
If you consider the matter, you will realize that a period is not a good choice just in case any statement involves a number with a decimal point. Actually, periods may have other uses as well, so semicolons are good candidates for this role.
TECHNICAL NOTE: The equal sign is used in many programming languages for assignment statements even though it can be confusing. The language APL (for A Programming Language) uses an arrow (() but most other languages use the equal sign.
One way of reading or thinking about assignment statements is to say
Make it be the case that the variable nextstep is now equal to "diagonal".
It is necessary to use the quotation marks around the character string diagonal in order to prevent the language from trying to find a variable named diagonal. (Notice that English punctuation is problematic for this last sentence so we use italics.)
Another example of an assignment statement is
totalwithtax = total + taxrate*total;
Interpret this statement as follows:
Assuming that total and taxrate are variables that have values, fetch both values and multiply them together. Then take that result and add to it the value of total. Assign this to the variable totalwithtax.
The right-hand side of the assignment statement is termed an expression. The plus sign is an example of an operator and, in this case, stands for addition of numbers. You may say, “of course, it stands for addition of numbers.” However, in JavaScript, as well as many other, though not all, programming languages, the plus sign, in a different context, means concatenation of strings:
"abc" + "def" yields "abcdef"
Assuming that title is a variable holding the value "Logic", then
"The name of the book is "+title
yields "The name of the book is Logic"
This double duty for the + operator is called operator over-loading and will be used in the first example in this chapter.
Most programming languages support expressions of more-or-less unlimited complexity with operators for arithmetic, comparison and logical operations. An example of an expression involving a comparison operator would be
score >= average
Making the assumption that score and average are variables holding numbers, then this expression has the value true if the value of score is greater than or equal to the value of average and false otherwise.
TECHNICAL NOTE: Programming languages differ in how true and false (also called Boolean values after mathematician George Boole) are encoded with some languages defining Booleans as one distinct type and others assigning Boolean values (true or false) to numbers.
Logical operators take true and false values as operands. A typical example would be the following:
(xpos < rightwall) && (xpos >leftwall)
In this example, the && symbol stands for the logical and operation. This operator will return true if both operands are true; otherwise, false. The sample expression here computes if a value xpos is in-between the values rightwall and leftwall. The language processor performs three operations to compute the final result: the two comparisons and then the logical operation on the two results. Later in this chapter, you will learn about the if statement, which uses Boolean values to control what statements get executed.
The next example justifies what is a common shorthand form of statement in several languages. Consider
turn = turn +1;
This may look strange! Remember that the = sign does not stand for equals in this context. The interpretation is
Take the value of the variable turn, add 1 to it, and then put this new value into turn.
The 1 is called a literal representing the numeric value 1. It is analogous to the literal value of the character string "diagonal".
Because adding 1 to a variable is a very common occurrence, many languages have shorthand forms of assignment statements. The following means to increment the value of the variable turn:
turn++;
Other shorthand forms exist and some will be demonstrated later in this text. This construct can be used within an expression as well as by itself.
The order of execution of operations is determined by a set of rules called precedence rules. These are fairly consistent across programming languages. For example, the expression
1 + 2 * 3
is executed with the multiplication going first and then the addition, producing 7, not 9. You can overrule the precedence rules by using parentheses.
TIP: It is a good practice to use parentheses to make the expressions easier to read even if the precedence rules would make them unnecessary in a particular case. More generally, though it may be possible to compress coding into a small number of characters, statements and/or lines, ease of understanding is important for debugging (finding errors) and maintenance. This generally argues for many, simpler statements in place of fewer, complex statements. Do not economize on typing!
To summarize the assignment statement, the right-hand side of the equal sign indicates the target and the left-hand side holds an expression.
Another type of statement demonstrated in the Flash example in Chapter 1 is the procedure call:
goToAndPlay(nextstep);
The goToAndPlay is a built-in procedure in Flash/ActionScript. Procedures, one of the most important concepts in programming, are the focus of a later chapter. However, some preliminary remarks are useful to make here in the context of statements. Most programming languages have what are termed built-in procedures and also provide ways for you, the programmer, to create your own procedures, that is, give a name to a sequence of statements and, effectively, extend the language. If you have done this, then you can invoke one of your procedures using this type of statement. The term 'method' is used to refer to a procedure that is associated with what is termed an object.
The term 'function' is sometimes reserved for a function that produces a value and, as a consequence, can be used in an expression. In JavaScript and ActionScript, the following
dievalue = 1+ Math.floor(Math.random()*6);
demonstrates the use of two of what are called class methods of the Math object. The Math.random produces a fractional value from 0 to 1 and the Math.floor truncates values to produce whole numbers. You will see this again when the discussion turns to dice games. In this text, the examples will show calls to built-in functions and methods and programmed-defined functions and methods.
Another important group of statements found in programming languages are the conditionals. Conditionals provide the programmer the ability to direct the invocation of statements based on conditions. These statements are the heart of programming logic. An example of an if statement in JavaScript is
if (current > best) best = current;
Assuming that current and best are two variables holding values that can be compared, say sales amounts or grades or test scores, then if the comparison is true, the value of current is assigned to the variable best. The code performed if the condition is true is termed the true-clause. If the condition is not true, no assignment takes place.
A way to express the actions of an if statement pictorially is to use flowchart symbols.
[pic]
Figure 6. Flow chart representation of if
The if statement typically is what is called a compound statement, with symbols or layout used to organize several statements. Another way to write the previous example in JavaScript is
if (current > best) {
best = current;
}
The curly brackets can enclose any number of statements. Good practice is to use the brackets even if there is just the single statement. You may need to add another statement to the true clause and this is easier using brackets.
if (current > best) {
best = current;
changes++;
}
TECHNICAL NOTE: Some programming languages (Python or , for example) use line breaks to define the statements executed when the condition is true.
A variant of the if statement is the if/else
if (current > best) {
best = current;
changes++ }
else {
status = "no change";
}
This statement has the following effect: if the condition is true, that is, if the value of current is greater than the value of best, then the variable best is assigned the value of current and a variable changes is incremented. If the condition is not true, then a variable named status gets the value "no change". Figure 7 represents this statement.
[pic]
Figure 7. Flow chart for if/else
The condition part of an if statement can be any expression that returns a true or false value. In some computer languages, there are rules on how to interpret any type of value as either true or false. Other languages are stricter. One example of a conditional expression would be
if ((score>80) && (score 90) {
grade = "A";
}
else if (score > 80) {
grade = "B";
}
else if ….
An alternative in this particular situation may be to use a mixture of computation and conditionals (see the chapter on arrays).
Many languages provide another form of conditional statement called a switch or case select. Here is an example in Java and JavaScript format.
switch (month) {
case "Sep":
case "Apr":
case "Jun":
case "Nov":
number_of_days = 30;
break;
case: "Feb":
number_of_days=28;
break;
default:
number_of_days = 31;
}
This code fragment uses the variable month to set the variable number_of_days. The variable month is presumed to hold the 3 letter abbreviation for the name of a month. The language processor checks the value of month against the values following case starting from the first. If there is a match, then no more matching is done and statements are executed until the statement break is reached or the end of the whole switch statement. The effect here is that if month indicates one of September, April, June or November, then the value 30 is assigned to number_of_days. If month corresponded to February, the number of days indicated would be 28. In all other cases, the default clause is executed. Other programming languages may implement the switch construct differently; for example, some languages allow multiple case-type labels for clauses and do not have control flow down from the first matched case, removing the need for a break; command.
The last category of statements to be described here provides a means for repeating groups of statements. These are powerful constructs and will be used repeatedly in this book. Their power is best shown together with concepts to be introduced later. However, here is a simple example. Suppose you needed [your code] to add up the integers from 1 to a specified value held in the variable top. A good strategy would be to begin by defining or selecting a variable to use in the calculation. Since you do not know the value of top, you cannot simply write
sum = 1 + 2 + …..
Instead, start off by assigning zero to the sum variable. Then add in the values from 1 on, checking to see if it is time to stop. The following code in JavaScript syntax performs the task.
sum = 0;
for (i=1;i best) {
best = current;
}
is an example of
a. an OUT statement
b. an IF statement
c. program output
d. a CURRENT statement
9. fall_sales = oct_sales + nov_sales + dec_sales;
is an example of
a. an IF statement
b. an SWITCH statement
c. an assignment statement
d. an output statement
Projects
10. Modify the calculator program to add up 5 numbers.
11. Using features from both examples, implement a calculator that adds, subtracts, multiplies or divides based on setting of a radio button group.
12. Look up on-line other operators available in JavaScript and incorporate them into your calculator.
13. Add features to the Coffee Shop example using dropdown menus and radio button groups (for example, shot of expresso, whipped cream).
14. Enhance the Coffee Shop example by adding more text, formatting, images and links. For example, in place of or in addition to the text, illustrate the sizes. Put in a hyperlink using an image to represent an ad.
15. Do some field research to a coffee shop to get information on prices. Determine if it is the case that the prices of different sized drinks are calculated using a scheme such as shown in the example.
For teachers only: Tips for Teachers
The calculator example is a good project for basic operations, but it does have the potential to make the students wonder at all this fuss to recreate something fairly basic. That is one reason to include the Coffee Shop example in which the built-in dropdown menu and radio button add pizzazz.
It may be pedagogically sound to show the project in stages: first, without forcing the conversion to numbers and second, with no attention to formatting dollars-and-cents. When the students see problems, show the way to fix the problems.
I would not call precedence rules trivial, but I choose not to spend much time on them. I do say that the programming languages have rules for determining things such as order of operations. I guide my students to 1) use several simple as opposed to fewer complex expressions and statements and 2) use parentheses. This is good practice for debugging and maintenance. If and when individual students ask if there are advantages to combining statements, I may go into explanations of what the compiled runtime would be and may even admit that there may be some overhead in multiple statements. However, I point out that most, though not all, of these applications are I/O bound, not computation-bound.
The field trip to a coffee shop to see if there is a formula for pricing could be required or an extra credit opportunity. Identifying and articulating a pattern of reasoning for something observed in regular life is good practice for learning programming logic.
-----------------------
current>best
replace best with current
replace best & increment
changes
current>best
Set status to no change
Set sum to zero and i to 1
Add i to sum.
Increment i.
Is i ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- cdf home page
- matlab introduction university of delaware
- 1 university of california davis
- getting started drfrostmaths
- development environment
- visual python adapted from vpython tutorial by b
- introduction stellenbosch university
- washington state university
- dixie state university computing and design
- introduction to ccd cmos detector calibration
Related searches
- work environment descriptions
- job description work environment examples
- ideal work environment answer
- articles about the environment 2019
- environment articles
- job description work environment statement
- job descriptions work environment samples
- samples of work environment descriptions
- work environment for job description
- office work environment description
- environment projects for students
- maryland department of the environment mde