7.1 Fill in the blanks in each of the following statements:
- All programs can be written in terms of three types of control structures: sequence, selection and repetition.
- The if...else double-selection statement is used to execute one action when a condition is true and another action when that condition is false.
- Repeating a set of instructions a specific number of times is called counter-controlled (or definite) repetiton.
- When it is not known in advance how many times a set of statements will be repeated, a(n) sentinel (or a(n) signal, flag or dummy) value can be used to terminate the repetition.
7.2 Write four JavaScript statements that each add 1 to variable x, which contains a number.
x = x + 1;
x += 1;
++x;
x++;
7.3 Write JavaScript statements to accomplish each of the following tasks:
- Assign the sum of x and y to z, and increment the value of x by 1 after the calculation. Use only one statement.
z = x++ + y; - Test whether the value of the variable count is greater than 10. If it is print "Count is greater than 10".
if ( count > 10 )
document.writeln( "Count is greater than 10" ); - Decrement the variable x by 1, then subtract it from the variable total. Use only one statement.
total -= --x; - Calculate the remainder after q is divided by divisor, and assign the result to q. Write this statement in two different ways.
q %= divisor;
q = q % divisor;
7.4 Write a JavaScript statement to accomplish each of the following tasks:
- Declare variables sum and x.
var sum, x; - Assign 1 to variable x.
x = 1; - Assign 0 to variable sum.
sum = 0; - Add variable x to variable sum, and assign the result to variable sum.
sum += x; or sum = sum + x; - Print "The sum is: ", followed by the value of variable sum.
document.writeln( "The sum is " + sum );
7.5 Combine the statements that you wrote in Exercise 7.4 into a JavaScript program that calculates and prints the sum of the integers from 1 to 10. Use the while statement to loop through the calculation and increment statements. the loop should terminate when the value of x becomes 11.
7.6 Determine the value of each variable after the calculation is performed. Assume that, when each statement begins executing, all variables have the integer value 5.
- product *= x++; product = 25, x = 6
- quotient /= ++x; quotient = 0.833333..., x = 6
7.7 Identify and correct the errors in each of the following segments of code:
Error: Missing the right brace of the while body. Correction: Add closing brace after the statement ++c;
while ( c <= 5 ) {
product *= c;
++c;
}
Error: The semicolon after else results in a logic error. The second output statement will always be executed. Correction: Remove the semicolon after else.
if ( gender == 1 )
document.writeln( "Woman" );
else
document.writeln( "Man" );
7.8 What is wrong with the following while repetition statement?
The value of z is never changed in the body of the while statement. Therefore, if the loop-continuation condition ( z >= 0 ) is true, an infinite loop is created. To prevent the creation of the infinite loop, z must be decremented so that it eventually becomes less than 0.
7.9 Identify and correct the errors in each of the following segments of code [Note: There may be more than one error in each piece of code]:
Error: There should be no semicolon after the if statement. Correction: Remove the semicolon after if ( age >= 65 )
if ( age >= 65 )
document.writeln( "Age greater than or equal to 65" );
else
document.writeln( "Age is less than 65" );
Error: The variable "total" has not been initialized. Correction: Initialize "total" to 0.
var x = 1, total = 0;
while ( x <= 10 )
{
total += x;
++x;
}
Error: The "while" statement should be lowercase and the body is missing curly braces. Correction: Make "while" lowercase and add braces to while statement.
var x = 1;
var total = 0;
while ( x <= 100 )
{
total += x;
++x;
}
Error: The "while" statement creates an infinite loop and is missing the closing brace. Correction: Decrement variable "y" instead of increment and add closing brace.
var y = 5;
while ( y > 0 )
{
document.writeln( y );
--y;
}
7.10 What does the following program print?
For Exercises 7.11-7.14, perform each of the following steps:
- Read the problem statement.
- Formulate the algorithm using pseudocode and top-down, stepwise refinement.
- Write a JavaScript program.
- Test, debug and execute the JavaScript program.
- Process three complete sets of data.
7.11 Drivers are concerned with the mileage obtained by their automobiles. One driver has kept track of several tankfuls of gasoline by recording the number of miles driven and the number of gallons used (both as integers) for each tankful. The program should calculate and output XHTML text that displays the number of miles per gallon obtained for each tankful and prints the combined number of miles per gallon obtained for all tankfuls up to this point. Use prompt dialogs to obtain data from the user.
7.12 Develop a JavaScript program that will determine whether a department-store customer has exceeded the credit linmit on a charge account. For each customer, the following facts are available:
- Account number
- Balance at the begining of the month
- Total of all items charged by this customer this month
- Total of all credits applied to this customer's account this month
- Allowed credit limit
The program should input each of the facts from a prompt dialog as an integer, calculate the new balance (= begining balance + charges - credits), display the new balance and determine whether the new balance exceeds the customer's credit limit. For customers whose credit limit is exceeded, the program should output XHTML text that displays the message "Credit limit exceeded."
7.13 A large company pays its salespeople on a commission basis. The salespeople receive $200 per week, plus 9 percent of their gross sales for that week. For example, a salesperson who sells $5000 worth of merchandise in a week receives $200 plus 9 percent of $5000, or a total of $650. You have been supplied with a list of the items sold by each salesperson. The values of these items are as follows:
Item | Value |
---|---|
1 | 239.99 |
2 | 129.75 |
3 | 99.95 |
4 | 350.89 |
Develop a program that inputs one salesperson's items sold for last week, calculates the salesperson's earnings and outputs XHTML text that displays the salesperson's earnings.
7.14 Develop a JavaScript program that will determine the gross pay for each of three employees. The company pays "straight time" for the first 40 hours worked by each employee and pays "time and a half" for all hours worked in excess of 40 hours. You are given a list of the employees of the company, the number of hours each employee worked last week and the hourly rate of each employee. Your program should input this information for each employee, determine the employee's gross pay and output XHTML text that displays the employee's gross pay. Use prompt dialogs to input the data.
7.15 The process of finding the largest value (i.e. the maximum of a group of values) is used frequently in computer applications. For example, a program that determines the winner of a sales contest would input the number of units sold by each salesperson. The salesperson who sells the most units wins the contest. Write a pseudocode program and then a JavaScript program that inputs a series of 10 single-digit numbers as characters, determines the largest of the numbers and outputs a message that displays the largest number. Your program shold use three variables as follows:
- counter: A counter to count to 10 (i.e. to keep track of how many numbers have been input and to determine when all 10 numbers have been processed);
- number: The current digit input into the program;
- largest: The largest number found so far.
7.16 Write a JavaScript program that uses looping to print the following table of values. Output the results in an XHTML table. Use CSS to center the data in each column.
7.17 Using an approach similar to Exercise 7.15, find the two largest values among the 10 digits entered. [Note: You may input each number only once.]
7.18 Modify the program in Fig.7.11 to validate its inputs. For every value input, if the value entered is other than 1 or 2, keep looping until the user enters a correct value.
7.19 What does the following program print?
7.20 What does the following program print?
7.21 (Dangling-Else Problem) Determine the output for each of the given segments of code when x is 9 and y is 11, and when x is 11 and y is 9. Note that the interpreter ignores the indentation in a JavaScript program. Also, the JavaScript interpreter always associates an else with the previous if, unless told to do otherwise by the placement of braces ({}). You may not be sure at first glance which if an else matches. This situation is referred to as the "dangling-else" problem. We have eliminated the indentation from the given code to make the problem more challenging. [Hint: Apply the indentation conventions you have learned.]
7.22 (Another Dangling-Else Problem) Modify the given code to produce the output shown in each part of this problem. Use proper indentation techniques. You may not make any changes other than inserting braces, changing the code indentation and inserting blank lines. The interpreter ignores indentation in JavaScript. We have eliminated the indentation from the given code to make the problem more challenging. [Note: It is possible that no modification is necessary for some of the segments of code.]
- Assuming that x = 5 and y = 8, the following output is produced:
@@@@@
$$$$$
&&&&&
7.22a Answer - Assuming that x = 5 and y = 8, the following output is produced:
@@@@@
7.22b Answer - Assuming that x = 5 and y = 8, the following output is produced:
@@@@@
&&&&&
7.22c Answer - Assuming that x = 5 and y = 7, the following output is produced [Note: The last three output statements after the else statements are all part of a block]:
#####
$$$$$
&&&&&
7.22d Answer
7.23 Write a script that reads in the size of the side of a square and output XHTML text that displays a hollow square of that size constructed of asterisks. Use a prompt dialog to read the size from the user. Your program should work for squares of all side sizes between 1 and 20.
7.24 A palindrome is a number or text phrase that reads the same backward and forward. For example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554 and 11611. Write a script that reads in a five digit integer and determines whether it is a palindrome. If the number is not five digits long, display an alert dialog indicating the problem to the user. Allow the user to enter a new value after dismissing the alert dialog. [Hint: It is possible to do this exercise with the techniques learned in this chapter. You will need to use both division and remainder operations to "pick off" each digit.]
7.25 Write a script that outputs XHTML text that displays the following checkerboard pattern:
Your program may use only three output statements to display the pattern, one of the form document.write( "* "); one of the form document.write( " "); and one of the form document.writeln(); //writes a newline characterYou may use XHTML tags (e.g. <pre>) for alignment purposes. [Hint: Repetition structures are required in this exercise.]
7.26 Write a script that outputs XHTML text that keeps dsplaying in the browser window the multiples of the integer 2, namely 2, 4, 8, 16, 32, 64, etc. Your loop should not terminate (i.e. you should create an infinite loop). What happens when you run this program?
7.26 Answer - The script continues to run but never outputs and the page becomes unresponsive.
7.27 A company wants to transmit data over the telephone, but it is concerned that its phones may be tapped. All of its data is transmitted as four-digit integers. It has asked you to write a program that will encrypt its data so that the data may be transmitted more securely. Your script should read a four-digit integer entered by the user in a prompt dialog and encrypt it as follows: Replace each digit by (the sum of that digit plus 7) modulus 10. Then swap the first digit with the third, and swap the second digit with the fourth. Then output XHTML text that displays the encrypted integer.
7.28 Write a program that inputs an encrypted four-digit integer (from Exercise 7.27) and decrypts it to form the original number.