Chap 9 Decision Making and Programming
Chap 9 Decision Making and Programming
TABLE OF CONTENTS
Thus, we will look at the mental skills of analysis and organization of work to
turn the knowledge acquired in ITApps to produce results.
1. INTRODUCTION TO PROBLEM SOLVING
An algorithm is a sequence of simple steps that can be followed to solve a
problem. These steps must be organized in a logical, and clear manner.
In this example, the algorithm consists of three steps. Also, note that the
description of the algorithm is done using a so-called pseudocode. A pseudocode
is a mixture of English (or any other human language), symbols, and selected
features commonly used in programming languages. Here is the above algorithm
written in pseudocode:
READ degrees_Farenheit
degrees_Celcius = (5/9)*(degrees_Farenheit-32)
DISPLAY degrees_Celcius
READ grade
IF (grade >= 95)
THEN student receives a distinction
This is the simplest case of selection control. In fact, in essence it is a sequential
form but the second step is only taken when the condition contained in the
brackets is true, that is the last step (starting at THEN) is selected for execution
only when the condition is satisfied.
In this case, there is also a decision to be made but a more complex one. In the
condition is true only the Accept user step is executed and if the condition is
false only the Deny user step is executed. That is, the condition helps us make
a selection which controls which of the two steps will be executed.
Now look more closely to the condition. Does it guarantees that the user is valid?
What if we had this condition instead, which looks pretty similar: IF (username
in database AND password in database)? What would happen is
somebody typed a valid username but the password of a different but also valid
user? Does this second condition satisfies our requirement that to access this
account one should be the right user and know the corresponding password?
When you write a condition always make sure that it performs exactly the check
that you intended it to! It is very easy to translate words in pseudocode that
does a different thing than what was intended!
READ result
CASE (result >=90)
PRINT ‘A’
CASE (result >=80)
PRINT ‘B’
CASE (result >=70)
PRINT ‘C’
CASE (result >=60)
PRINT ‘D’
CASE (result <60)
PRINT ‘F’
In this case, there are five conditions which are checked, one after the other.
1.3 Repetition.
In Repetition one or more steps are performed repeatedly.
total = 0
average = 0
FOR 1 to 10
Read number
total = total + number
ENDFOR
average = total / 10
Example 2. Read numbers and add them up until their total value reaches (or
exceeds) a set value represented by S.
1. Problem statement. You are the receiving clerk for an electronics parts
distributor that imports large quantities of wire and cable produced abroad and
sold in the UK. Most of the wire you receive is measured in meters; however,
your customers order wire by foot. Your supervisor wants you to compute the
length in feet of each roll of wire or cable that you stock. You have to write a
program to perform this conversion.
Next, you need to know the relationship between meters and feet. If you do not
know this already you open up a book that explains how you can convert length
measurements (for example B. Franco, Key to Metric Measurement, Emeryville,
CA.: Key Curriculum Press, 2000) or you search on the Web (for example
http://www.convertit.com/Go/ConvertIt/Measurement/Converter.ASP -- but be
careful to find a trustworthy site!). For example, if you look it up in a table of
conversions factors, you will find that one meter equals 39.37 inches. We also
know that there are 12 inches to a foot. These findings are summarized below:
We then must decide whether any steps of the algorithm need further
refinement. Steps 1, and 3 need no further refinement. The refinement of step 2
shows how to perform the conversion:
/*
Converts wire length from meters to feet.
The user enters the wire length in meters.
*/
function convert(wmeter)
{
// Helper variables
var inchmt = 39.37
var inchft = 12
var wfeet=0
var winchs=0
We can now use this function in a Web page and use it to convert meters to
feet:
</head>
<body>
<script type="text/javascript">
document.write("Length in feet is: ",convert(10));
</script>
</body>
Let’s look at the different elements that we used to create this program.
Variables. Variables are quantities that can retain any value each time a
program runs:
var inchmt
Also wfeet, and inchft are variables. It is very important that variables have
meaningful names, because they make program easier to read, and understand.
If, for example, you name your variables m and f, it would not be
straightforward to remember what they represent.
Each language has special rules that restrict your selection of variable names. In
Javascript a variable name can be made up of small or capital letters, digits, and
underscore characters and the first character must always be a letter or the
underscore. Other characters, such as blanks, must not appear within a name.
Types. Variable inchmt holds a real value, and inchft holds an integer value.
Reals contain a fractional part, whereas integers are whole numbers.
Comments. Any line that starts with // is taken as a comment and thus
ignored by the computer. A comment can also be anything contain between /*
and */ for example:
/*
Converts wire length from meters to feet.
The user enters the wire length in meters.
*/
and
// Helper variables
Comments are very important! They give out information about the program to
you and they will come very handy when you need to change your code a few
months after creating it. Other people who have to work with your code will also
benefit. You should always use comments in your programs to explain anything
that is not straightforward to understand.
5. Testing and verification. Compare the program results with those that you
compute manually or by using a calculator. Keep in mind that programs often
have errors. We distinguish between two types of errors: Syntactic
(grammatical), and semantic (logical) errors.
in the example above, then everything would seem to work as required but the
calculated result would be incorrect.
3. USING FUNCTIONS FOR MODULAR PROGRAMMING
In the previous section we discussed the divide-and-conquer approach to
program desing. The main idea was to divide the overall task in smaller chunks
that we can handle more easily. Sometimes there are tasks that are being
repeated in several points in the program – we would want to write code only
once!
For example, if we want to find the smaller of two variables we can and uses
Math.min function:
Function MIN gets three arguments: num1, num2, and num3, and returns the
minimum of the arguments that is assigned to the variable minimum
function myfunction(argument1,argument2,etc)
{
some statements
}
Example: Let’s write a function that calculates the area of a square given the
length of its side.
function square_area(side)
{
return side*side
}
Functions that will return a result must use the return statement. This
statement specifies the value that will be returned to the point where the
function was called.
Single Selection
Example: The following code fragment reads the time from the system clock and
if it is earlier than 10am it displays the message “Good morning!”
Example: The following code fragment reads the time from the system clock and
if it is earlier than 10am it displays the message “Good morning!” and in every
other case it prints “Good day!”.
Nested IF Statement
function display_result(mark) {
if (mark >= 90) {
display.document(“A”);
} else if (mark >= 80) {
display.document(“B”);
} else if (mark >= 70) {
display.document(“C”);
} else if (mark >= 60) {
display.document(“D”);
} else {
display.document(“F”);
}
}
Example: Consider the following program that computes the roots of a quadratic
equation:
function quadratic(a, b, c) {
// program to compute the roots of a quadratic equation
var root1, root2, disc
// compute discriminant
disc = b * b - (4.0 * a * c);
Multiple Selection
The selection structure considered thus far, involved selecting one of two
alternatives. It is also possible to use the IF construct to design selection
structures that contain more than two alternatives. The switch construct is
used to select among multiple alternatives on the basis of a single expression
value. The general form of the case structure is
switch (expression)
{
case label1:
code to be executed if expression = label1
break
case label2:
code to be executed if expression = label2
break
default:
code to be executed
if expression is different
from both label1 and label2
}
The expression is evaluated and compared to each selector, where each selector
is a list of possible values of the expression. Only one statement is executed. The
DEFAULT statement is optional and it is obeyed if none of the other CASE
statements produces a match.
Example: The following code fragment will return a different response depending
on the day it is run:
We can start with an example: Consider the following price structure for concert
tickets:
Using a nested IF statement, one can have the following structure to assign the
desired value to price or displays an error message if the section is not listed in
the table:
if (section == 50) {
price = 50.00;
} else if ((100 <= section) &&(section <= 199)) ||
(200 <= section) && (section <= 299)) {
price = 25.00;
} else if ((300 <= section) && (section <= 399)) {
price = 20.00;
} else if ((400 <= section) && (section <= 499)) {
price = 15.00;
} else {
document.write("Invalid section number”);
}
Using the switch statement, we can rewrite the above program in the following
way:
switch (Math.floor(section/100)){
case 0:
price = 50.00;
break;
case 1:
price = 25.00;
break;
case 2:
price = 25.00;
break;
case 3:
price = 20.00;
break;
case 4:
price = 15.00;
break;
default:
document.write("Invalid section number");
}
Clearly, the case structure is more readable, and easier to code than the nested
IF structure.
6. STRUCTURED PROGRAMMING: REPETITION STRUCTURE
The repetition of a block of statements a number of times is called a loop, and is
so important that Javascript support several different constructs to support this
feature.
In this case, the index variable is initialized at initialization and the code
is executed until condition is reached. At the end of each iteration the
variable is increased by increment.
Example 1: The following program segment will display the first 10 positive
integers:
Example 2: In the following example, the initial value for variable i is 1, and it is
incremented by 2, so the next values will be 3, 5, and so on. The following
segment would display the odd positive integers between 1 and 10.
The following segment will compute the average of the first ten numbers:
The while statement will execute a block of code while a condition is true.
while (condition)
{
code to be executed
}
i = 0
while (i <= 5)
{
document.write(" ", i)
i++
}
The do...while statement will execute a block of code once, and then it will
repeat the loop while a condition is true
do
{
code to be executed
}
while (condition)
Example 4. Let’s redo Example 1 using the do..while construct
i = 0
do
{
document.write(" ", i)
i++
}
while (i <= 5)
Summary
Very often when you write code, you want the same block of code to run a
number of times. You can use looping statements in your code to do this. In
JavaScript we have the following looping statements:
• while - loops through a block of code while a condition is true
• do...while - loops through a block of code once, and then repeats the loop
while a condition is true
• for - run statements a specified number of times