Professional Documents
Culture Documents
TRUE/FALSE
1. Many seasoned programmers start counter values at 1 because they are used to doing so when working
with arrays.
3. You can use virtually any number of nested loops; however, at some point, your machine will no
longer be able to store all the necessary looping information.
4. In order to improve loop performance, it’s important to make sure the loop does not include
unnecessary operations or statements.
6. The statements that make up a loop body will continue to execute as long as the expression value
remains false.
7. A statement that will alter the value of the loop control variable is included in the body of a loop.
8. Shortcut operators are a programmer’s only choice when incrementing or accumulating a variable’s
value.
10. When nesting loops, the variable in the outer loop changes more frequently.
MULTIPLE CHOICE
2. Use a(n) ____ loop to execute a body of statements continually as long as the Boolean expression that
controls entry into the loop continues to be true.
a. empty c. definite
b. while d. control
ANS: B PTS: 1 REF: 301
6. It is important that the loop control ____ be altered within the body of the loop.
a. value c. constant
b. variable d. argument
ANS: B PTS: 1 REF: 301
10. ____ is the process of ensuring that a value falls within a specified range.
a. Value checking c. Validating data
b. Data integrity d. A range check
ANS: C PTS: 1 REF: 308
11. The process of repeatedly increasing a value by some amount is known as ____.
a. checking c. accumulating
b. adding d. containing
ANS: C PTS: 1 REF: 312
12. When you want to increase a variable’s value by exactly 1, use the ____.
a. power statement c. binary operators
b. accumulating operator d. prefix increment operator
ANS: D PTS: 1 REF: 312
13. You use a unary minus sign preceding a value to make the value ____.
a. negative c. valid
b. positive d. constant
ANS: A PTS: 1 REF: 313
14. A(n) ____ loop is a special loop that is used when a definite number of loop iterations is required.
a. while c. else
b. for d. do…while
ANS: B PTS: 1 REF: 317
15. A for loop provides a convenient way to create a(n) ____ loop.
a. counter-controlled c. while
b. posttest d. infinite
ANS: A PTS: 1 REF: 317
16. You can initialize more than one variable in a for loop by placing a(n) ____ between the separate
statements.
a. semicolon c. period
b. equal sign d. comma
ANS: D PTS: 1 REF: 318
17. The ____ loop checks the value of the loop control variable at the bottom of the loop after one
repetition has occurred.
a. while c. for
b. do…while d. else
ANS: B PTS: 1 REF: 322
18. In a do…while loop, the loop will continue to execute until ____.
a. the loop control variable is true c. the user types EXIT
b. the loop control variable is false d. the program terminates
ANS: B PTS: 1 REF: 300
20. The order of the conditional expressions in the following is most important within a(n) ____ loop.
while(requestedNum > LIMIT || requestedNum < 0)…
a. nested c. pretest
b. posttest d. indefinite
ANS: A PTS: 1 REF: 330
21. A(n) ____ loop is one that performs no actions other than looping.
a. nested c. indefinite
b. do-nothing d. posttest
ANS: B PTS: 1 REF: 331
22. In the expressions b = 8 and c = --b, what value will be assigned to the variable c?
a. 8 c. 9
b. 7 d. 10
ANS: B PTS: 1 REF: 314
23. When creating a for loop, which statement will correctly initialize more than one variable?
a. for a=1, b=2 c. for(a=1, b=2)
b. for(a=1; b=2) d. for(a = 1&& b = 2)
ANS: C PTS: 1 REF: 318
24. As long as methods do not depend on one another, ____ is a technique that can improve loop
performance by combining two loops into one.
a. loop fusion c. short-circuit evaluation
b. prefix incrementing d. do-nothing looping
ANS: A PTS: 1 REF: 332
25. Which of the following is NOT a valid method to increase a variable named score by 1?
a. ++score c. ++score = score + 1
b. score++ d. score = score + 1
ANS: C PTS: 1 REF: 312
COMPLETION
ANS: iteration
3. If a(n) ____________________ is altered both within the for statement and within the block it
controls, it can be very difficult to follow the program’s logic.
ANS: variable
ANS:
do…while
do while
5. When loops are nested, each pair contains a(n) ____________________ loop and an outer loop.
ANS: inner
MATCHING
SHORT ANSWER
ANS:
Within a looping structure, a Boolean expression is evaluated. If it is true, a block of statements
called the loop body executes and the Boolean expression is evaluated again. As long as the expression
is true, the statements in the loop body continue to execute. When the Boolean evaluation is false,
the loop ends.
ANS:
You might suspect an infinite loop if the same output is displayed repeatedly or if the screen simply
remains idle for an extended period of time without displaying the expected output. If you think your
application is in an infinite loop, you can press and hold Ctrl, and then press C or Break; the looping
program should terminate.
3. What would happen if a semicolon is mistakenly placed at the end of a partial statement of a while
loop with a Boolean expression and with an empty body?
ANS:
If a semicolon is mistakenly placed at the end of the partial statement while (loopCount <
3);, the loop is also infinite. This loop has an empty body, or a body with no statements in it. So, the
Boolean expression is evaluated, and because it is true, the loop body is entered. Because the loop
body is empty, no action is taken and the Boolean expression is evaluated again. Nothing has changed,
so it is still true, the empty body is entered, and the infinite loop continues.
4. Why would a loop with altered user input be considered a type of indefinite loop? Give an example.
ANS:
Perhaps you want to continue performing some task as long as the user indicates a desire to continue.
In this case, while you are writing the program, you do not know whether the loop eventually will be
executed two times, 200 times, or at all. Unlike a loop that you program to execute a fixed number of
times, a loop controlled by the user is a type of indefinite loop because you don’t know how many
times it will eventually loop.
Consider an application in which you ask the user for a bank balance and then ask whether the user
wants to see the balance after interest has accumulated for each year.
5. What are some of the shortcuts Java provides programmers for incrementing and accumulating? Give
examples of statements.
ANS:
The statement count += 1; is identical in meaning to count = count + 1. The += is the add
and assign operator; it adds and assigns in one operation. Similarly, balance += balance *
INT_RATE; increases a balance by the INT_RATE percentage. Besides using the shortcut
operator +=, you can use the subtract and assign operator ( -= ), the multiply and assign operator ( *=
), the divide and assign operator ( /= ), and the remainder and assign operator ( %= ). Each of these
operators is used to perform the operation and assign the result in one step.
ANS:
A for loop is a special loop that is used when a definite number of loop iterations is required.
Although a while loop can also be used to meet this requirement, the for loop provides you with a
shorthand notation for this type of loop. When you use a for loop, you can indicate the starting value
for the loop control variable, the test condition that controls loop entry, and the expression that alters
the loop control variable—all in one convenient place.
7. Besides initializing, testing, and incrementing, you can also perform other tasks with a for loop.
What are some of these tasks? Use code samples as examples.
ANS:
Initialization of more than one variable by placing commas between the separate statements, as in the
following:
for(g = 0, h = 1; g < 6; ++g)
Performance of more than one test using AND or OR operators, as in the following:
for(g = 0; g < 3 && h > 1; ++g)
Decrementation or performance of some other task, as in the following:
for(g = 5; g >= 1; --g)
Altering more than one value, as in the following:
for(g = 0; g < 10; ++g, ++h, sum += g)
You can leave one or more portions of a for loop empty, although the two semicolons are still
required as placeholders. For example, if x has been initialized in a previous program statement, you
might write the following:
for(; x < 10; ++x)
8. Why would a programmer use curly braces in the body of a do…while loop?
ANS:
When the body of a do…while loop contains a single statement, you do not need to use curly braces
to block the statement. Even though curly braces are not required in this case, many programmers
recommend using them. Doing so prevents the third line of code from looking like it should begin a
new while loop.
ANS:
Just as if statements can be nested, so can loops. You can place a while loop within a while loop,
a for loop within a for loop, a while loop within a for loop, or any other combination. When
loops are nested, each pair contains an inner loop and an outer loop. The inner loop must be entirely
contained within the outer loop; loops can never overlap.
10. How could you rewrite the following code to have the arithmetic performed only once, even if the loop
executes 1,000 times?
while (x < a + b)
// loop body
ANS:
int sum = a + b;
while(x < sum)
// loop body
11. Describe the purpose of a loop control variable. How are Boolean values and a while loop involved?
ANS:
When creating a definite loop, a loop control variable is initialized. Its value determines whether loop
execution continues. While the Boolean value that results from comparing the loop control variable
and another value is true, the body of the while loop continues to execute. In the body of the loop,
you must include a statement that alters the loop control variable.
12. Describe a counter-controlled loop. Explain the process of incrementing and decrementing, and
explain the best method for executing a loop a specific number of times.
ANS:
In a counter-controlled loop, a loop control variable is changed by counting. Incrementing the variable
is a common way to alter the value of a loop control variable by adding 1 to it. In decrementing, the
loop is controlled by subtracting 1 from a loop control variable.
To execute a loop a specific number of times, the clearest and best method is to start
the loop control variable at 0 or 1, increment by 1 each time through the loop, and stop
when the loop control variable reaches the appropriate limit.
13. Loop control variables can be evaluated at the start or the end of the loop. Describe both pretest loops
and posttest loops. How do do…while loops execute?
ANS:
In a pretest loop, the loop control variable is evaluated at the top of the loop before the
body has a chance to execute. Both while loops and for loops are pretest loops in that the
loop control variable is tested before the loop body executes.
A posttest loop is used if you need to ensure that a loop body executes at least one time. In this case,
you write a loop that checks at the bottom of the loop after the first iteration. The do…while loop is a
posttest loop that tests the loop control variable after the loop body executes.
14. Explain why an infinite loop might not actually execute infinitely.
ANS:
An infinite loop may perform tasks that will eventually lead to a computer running out of memory,
causing execution to stop. Another possibility is the computer’s processing timing out, resulting in the
loop ending.
PTS: 1 REF: 302
15. How are indefinite loops used for validating data? Why is a loop structure typically the better choice
for validating data than an if statement?
ANS:
Programmers commonly use indefinite loops when validating input data. Validating data is
the process of ensuring that a value falls within a specified range. For example, suppose you
require a user to enter a value no greater than 3. If the user enters 3 or less at the first prompt, the loop
never executes. However, if the user enters a number greater than 3, the shaded loop executes,
providing the user with another chance to enter a correct value. While the user continues to enter
incorrect data, the loop repeats.
Before the loop is entered, the first input is retrieved. This first input might be a value that prevents
any executions of the loop. This first input statement prior to the loop is called a priming read or
priming input. Within the loop, the last statement retrieves subsequent input values for the same
variable that will be checked at the entrance to the loop.
Novice programmers often make the mistake of checking for invalid data using a decision instead of a
loop. That is, they ask whether the data is invalid using an if statement; if the data is invalid, they
reprompt the user. However, they forget that a user might enter incorrect data multiple times. Usually,
a loop is the best structure to use when validating input data.
CASE
1.
Using the flowchart and code above, describe the execution of the loop. Identify the loop control
variable and the value of the variable as the code is executed.
ANS:
To write a definite loop, you initialize a loop control variable, a variable whose value determines
whether loop execution continues. While the Boolean value that results from
comparing the loop control variable and another value is true, the body of the while loop
continues to execute. In the body of the loop, you must include a statement that alters the
loop control variable. The code segment displays the series of integers 1 through 10. The variable val
is the loop control variable and starts the loop holding a value of 1; and while the value remains under
11, val continues to be output and increased.
ANS:
The above code is an infinite loop. The expression 10 > 1 will always evaluate to true. Since this
expression is part of a while loop, the body of the loop is entered and “Enter a new value” is
displayed. Next, the expression is evaluated again. The expression 10 > 1 is still true, so the body is
entered again. “Enter a new value” is displayed repeatedly. The loop never finishes because 10 > 1 is
never false.
3.
Using the information provided above, write the while loop that will correctly follow the execution
of the flowchart.
ANS:
loopCount = 1;
while(loopCount < 10)
{
System.out.println("Welcome");
loopCount = loopCount + 1;
}
4. counterLoop = 1;
while(counterLoop < 10);
{
System.out.println("Enter a new value");
counterLoop = counterLoop + 1;
}
What is the problem in the above while loop? How would you correct the problem?
ANS:
The placement of the statement-ending semicolon is important when you work with the while
statement. In the code, a semicolon is mistakenly placed at the end of the partial statement
while(counterLoop < 10). This makes the loop infinite. This loop has an empty body, or a
body with no statements in it. The Boolean expression is evaluated; and because it is true, the loop
body is entered. Because the loop body is empty, no action is taken, and the Boolean expression is
evaluated again. Nothing has changed, so it is still true, the empty body is entered, and the infinite
loop continues.
5. Write a definite while loop that initializes a loop control variable named decreaseOne to 10 and
continues until decreaseOne > 0. Decrement the loop control variable by 1 and include the
println output “Keep going” within the loop.
ANS:
decreaseOne = 10;
while(decreaseOne > 0);
{
System.out.println("Keep going");
decreaseOne = decreaseOne - 1;
}
6. Create an indefinite while loop that will validate that the loop control variable named userNum is
less than the constant MAXVALUE. While true, create a println statement to output “Please enter a
higher value”. Once MAXVALUE is reached, create a final println statement that will output “Max
value reached”.
ANS:
while (userNum < MAXVALUE)
{
System.out.println("Please enter a higher value");
{
System.out.println("Max value reached");
Using the above code, describe how the three println output commands will appear. Explain the
values stored in the variables during code execution.
ANS:
The myVal variable is initialized to 10. The first println statement will display:
“My initial value is 10”.
myVal is then incremented by 1 and the value is stored in yourVal. At this point, both myVal and
yourVal have a value of 11.
Using the above code, what values will appear in compare1 and compare2 when the println
commands execute? Describe how the values of compare1 and compare2 change as the
statements are executed.
ANS:
System.out.println("Compare 1 value = " + compare1) will return a value of
false.
In this first Boolean comparison, b uses a prefix ++. The value of b increments from 10 to 11. Thus
comparing 11 to the value of a (10) results in a Boolean value of false.
In the second Boolean comparison, b uses postfix ++. The value of b increments from 10 to 11, but
the comparison is done before the increment. Therefore, the value of b before the increment (10) is
compared to the value of c (which is the value 11), so the Boolean value is again false.
9. Write a for loop that will initialize the variables value1 to 11 and value2 to 19. Create a test
section of the for statement that will test if value1 is greater than 10 and value2 is less than 20.
Finally, end the for statement by incrementing value1 by 1. In the loop body, write a println
statement that will display the contents of value1.
ANS:
for(value1 = 11, value2 = 19; value1 > 10 && value2 < 20; ++value1)
{
System.out.println(value1);
}
}
}
Complete the code above by writing a do…while posttest loop that will output the value of the
variable currentValue in a println statement. After the output statement, add a decrement
statement to decrease the value of currentValue by 1. Continue the loop until currentValue is
equal to 0.
ANS:
do
{
System.out.println("The value of currentValue is " +currentValue);
++currentValue;
}while(response > 0);