Moment 3 Flashcards

Kap 3 & 4

1
Q

A procedure for solving a problem in terms of the actions to execute and the order in which they execute is called an?

A

algorithm

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Specifying the order in which statements execute in a program is called?

A

program control

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Pseudocode is an informal language that helps you with?

A

develop algorithms without having to worry about the strict details of Java language syntax.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Normally, statements in a program are executed one after the other in the order in which they’rewritten. This process is called?

A

sequential execution

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is transfer of control?

A

Various Java statements enable you to specify that the next statement to execute is not necessarily the next one in sequence. This is called transfer of control.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Bohm and Jacopini demonstrated that all programs could be written in terms of only three control structures - Which

A

the sequence structure, the selection structure and the iteration structure.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How does the computer execute Java statements?

A

Unless directed otherwise, the computer executes Java statements one after the other in the order in which they’re written—that is, in sequence.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is a activity diagram?

A

An activity diagram models the workflow of a portion of a software system.

(p. 123; also called the activity)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Activity diagrams are composed of?

A

symbols — such as action-state symbols, diamonds and small circles—that are connected by transition arrows, which represent the flow of the activity.

(p. 123)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

The arrows in an activity diagram represent?

A

transitions, which indicate the order in which the actions represented by the action states occur.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

The solid circle located at the top of an activity diagram represents?

A

the activity’s initial state —the beginning of the workflow before the program performs the modeled actions.

(p. 123)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

The solid circle surrounded by a hollow circle that appears at the bottom of the diagram represents?

A

the final state —the end of the workflow after the program performs its actions.

(p. 123)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Rectangles with their upper-right corners folded over are UML notes?

A

explanatory remarks that describe the purpose of symbols in the diagram.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Java has three types of selection statements, which?

A

if
if…else
switch

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does the if single-selection statement do?

A

The if single-selection statement selects or ignores one or more actions.

(p. 124)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What does the if…else double-selection statement do?

A

The if…else double-selection statement selects between two actions or groups of actions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What does the switch selection statement do?

A

The switch selection statement selects among many different actions or groups of actions.

(p. 124)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Java provides the while, do…while, for and enhanced for iteration statements that enable programs to?

A

perform statements repeatedly as long as a loop-continuation condition remains true.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What does the “while”, “do…while” and “for” statements do?

A

The “while” and “for” statements perform the action(s) in their bodies zero or more times, based on their loop-continuation conditions (p. 124). The “do…while” statement its body one or more times.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is control-statement stacking?

A

Single-entry/single-exit control statements are attached to one another by connecting the exit point of one to the entry point of the next. This is known as control-statement stacking.

(p. 124)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

The if statement is a?

A

single-entry/single-exit control statement.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What action dose the “if…else” double-selection statement perform?

A

The “if…else” double-selection statement performs one action (or group of actions) when the condition is true and another action (or group of actions) when the condition is false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How can a program test multiple cases?

A

A program can test multiple cases with nested if…else statements (p. 127).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the “Dangling-“else” Problem”

A

The Java compiler associates an else with the immediately preceding if unless told to do otherwise by the placement of braces.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is a logic error?

A

A logic error has its effect at execution time.

p. 129

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is the differences between a fatal logic error and a nonfatal logic error?

A

A fatal logic error (p. 129) causes a program to fail and terminate prematurely. A nonfatal logic error (p. 129) allows a program to continue executing, but causes it to produce incorrect results.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What dose the The conditional operator ?: do?

A

The conditional operator ?: takes three operands. Together, the operands and the ?: symbol form a conditional expression. The first operand (to the left of the ?) is a boolean expression, the second is the value of the conditional expression if the condition is true and the third is the value of the conditional expression if the condition is false.

EX: System.out.println (studentGrade >= 60 ? “Passed” : “Failed”);

(p. 129)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What does the “while” iteration statement do?

A

The while iteration statement allows you to specify that a program should repeat an action while some condition remains true.

(p. 130)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What does the UML’s merge symbol do?

A

The UML’s merge symbol joins two flows of activity into one.

(p. 130)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

How do you distinguish the differences between the UML’s decision and merge symbols

A

The decision and merge symbols can be distinguished by the number of incoming and outgoing transition arrows. A decision symbol has one transition arrow pointing to the diamond and two or more transition arrows pointing out from the diamond to indicate possible transitions from that point. Each transition arrow pointing out of a decision symbol has a guard condition. A merge symbol has two or more transition arrows pointing to the diamond and only one transition arrow pointing from the diamond, to indicate multiple activity flows merging to continue the activity. None of the transition arrows associated with a merge symbol has a guard condition.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Counter-controlled iteration uses a variable called a?

A

a counter (or control variable) to control the number of times a set of statements execute.

(p. 131)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Counter-controlled iteration is often called?

A

definite iteration, because the number of iterations is known before the loop begins executing.

(p. 131)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

A total is a variable used to?

A

accumulate the sum of several values. Variables used to store totals are normally initialized to zero before being used in a program.
(p. 131)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

A local variable’s declaration must appear?

A

before the variable is used in that method. A local variable cannot be accessed outside the method in which it’s declared.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Dividing two integers results in?

A

integer division—the calculation’s fractional part is truncated.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

In sentinel-controlled iteration, a special value called ________ is used?

A

In sentinel-controlled iteration, a special value called a sentinel value (also called a signal value, a dummy value or a flag value) is used to indicate “end of data entry.”
(p. 135)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

A sentinel value must be chosen that?

A

That it cannot be confused with an acceptable input value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What is essential to the development of well-structured programs?

A

Top-down, step-wise refinement.

p. 135

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Division by zero is a?

A

logic error.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

How to perform a floating-point calculation with integer values?

A

cast one of the integers to type double.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

What is promotion on selected operands?

A

Java knows how to evaluate only arithmetic expressions in which the operands’ types are identical.
To ensure this, Java performs an operation called promotion on selected operands.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

The unary cast operator is formed by?

A

placing parentheses around the name of a type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What are compound assignment operators?

A

The compound assignment operators abbreviate assignments. Statements of the form:
variable = variable operator expression;
where operator is one of the binary operators +, -, *, / or %, can be written in the form
variable operator= expression;

(p. 146)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What does the “+=” operator do?

A

The += operator adds the value of the expression on the right of the operator to the value of the variable on the left of the operator and stores the result in the variable on the left of the operator.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

What are the Increment and Decrement Operators, and what do they do?

A

The unary increment operator, ++, and the unary decrement operator, –, add 1 to or subtract 1 from the value of a numeric variable.

(p. 147).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

What is the difference between prefix and postfixed decrement operator?

A

An increment or decrement operator that’s prefixed to a variable is the prefix increment or prefix decrement operator, respectively. An increment or decrement operator that’s postfixet to a variable is the postfix increment or postfix decrement operator, respectively.

(p. 147)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

Using the prefix increment or decrement operator to add or subtract 1 is known as?

A

preincrementing or predecrementing, respectively.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

Using the postfix increment or decrement operator to add or subtract 1 is known as?

A

postincrementing or postdecrementing, respectively.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

All programs can be written in terms of three types of control structures: ________ ,________ and ___________ .

A

sequence, selection, iteration.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

The ___________ statement is used to execute one action when a condition is true and another when that condition is false.

A

if…else.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

Repeating a set of instructions a specific number of times is called ____________ iteration.

A

counter-controlled (or definite).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

When it’s not known in advance how many times a set of statements will be repeated, a(n) ___________ value can be used to terminate the iteration.

A

sentinel, signal, flag or dummy.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

The ______________ is built into Java; by default, statements execute in the order they appear.

A

sequence structure.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

If the increment operator is ________________ to a variable, first the variable is incremented by 1, then its new value is used in the expression.

A

prefixed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

When the declaration int y = 5; is followed by the assignment y += 3.3; the value of y is ________________ .

A

[Note: You might expect a compilation error on the assignment statement. The Java Language Specification says that compound assignment operators perform an implicit cast on the right-hand expression’s value to match the type of the variable on the operator’s left side. So the calculated value 5 + 3.3 = 8.3 is actually cast to the int value 8.].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

T or F

An algorithm is a procedure for solving a problem in terms of the actions to execute and the order in which they execute.

A

True

57
Q

T or F

A set of statements contained within a pair of parentheses is called a block.

A

False. A set of statements contained within a pair of braces ({ and }) is called a block.

58
Q

T or F

A selection statement repeats an action while a condition remains true.

A

False. An iteration statement specifies that an action is to be repeated while some condition remains true.

59
Q

T or F

A nested control statement appears in the body of another control statement.

A

True

60
Q

T or F

Java provides the arithmetic compound assignment operators +=, -=, *=, /= and %= for abbreviating assignment expressions.

A

True.

61
Q

T or F

The primitive types (boolean, char, byte, short, int, long, float and double) are portable across only Windows platforms.

A

False. The primitive types (boolean, char, byte, short, int, long, float and double) are portable across all computer platforms that support Java.

62
Q

T or F

Specifying the order in which statements execute in a program is called program control.

A

True.

63
Q

T or F

The unary cast operator (double) creates a temporary integer copy of its operand.

A

False. The unary cast operator (double) creates a temporary floating-point copy of its operand.

64
Q

T or F

Instance variables of type boolean are given the value true by default.

A

False. Instance variables of type boolean are given the value false by default.

65
Q

T or F

Pseudocode helps you think out a program before attempting to write it in a programming
language.

A

True.

66
Q

Write four different Java statements that each add 1 to integer variable x.

A
  1. x = x + 1;
  2. x += 1;
  3. ++x;
  4. x++;
67
Q

Write Java statements to accomplish each of the following tasks:

Use one statement to assign the sum of x and y to z, then increment x by 1.

A

z = x++ + y;

68
Q

Write Java statements to accomplish each of the following tasks:

Test whether variable count is greater than 10. If it is, print “Count is greater than 10”.

A
1    if (count > 10) {
2   System.out.println("Count is greater than 10");
3    }
69
Q

Write Java statements to accomplish each of the following tasks:

Use one statement to decrement the variable x by 1, then subtract it from variable total and store the result in variable total.

A

total - = –x;

70
Q

Write Java statements to accomplish each of the following tasks:

Calculate the remainder after q is divided by divisor, and assign the result to q. Write this statement in two different ways.

A

1 q %= divisor;

2 q = q % divisor;

71
Q

Write a Java statement to accomplish each of the following tasks:

Declare variable sum of type int and initialize it to 0.

A

int sum = 0;

72
Q

Write a Java statement to accomplish each of the following tasks:

Declare variable x of type int and initialize it to 1.

A

int x = 1;

73
Q

Write a Java statement to accomplish each of the following tasks:

Add variable x to variable sum, and assign the result to variable sum.

A

sum += x; or sum = sum + x;

74
Q

Write a Java statement to accomplish each of the following tasks:

Print “The sum is: “, followed by the value of variable sum.

A

System.out.printf(“The sum is: %d%n”, sum);

75
Q

What do counter-controlled iteration (p. 165) require?

A
  • a control variable,
  • the initial value of the control variable,
  • the increment by which the control variable is modified each time through the loop (also known as each iteration of the loop)
  • the loop-continuation condition that determines whether looping should continue.
76
Q

The for statement (p. 166) specifies all the details of counter-controlled iteration?

A

in its header.

77
Q

How does a for loop work?

A
  • When the for statement begins executing, its control variable is declared and initialized. If the loop-continuation condition is initially true, the body executes.
  • After executing the loop’s body, the increment expression executes.
  • Then the loop-continuation test is performed again to determine whether the program should continue with the next iteration of the loop.
78
Q

The general format of the for statement is?

A

for (initialization ; loopContinuationCondition ; increment)
{
statements
}

79
Q

Whats does the “for” initialization expression do?

A

the initialization expression names the loop’s control variable and provides its initial value,

80
Q

Whats does the “for” loopContinuationCondition do?

A

loopContinuationCondition determines whether the loop should continue executing

81
Q

Whats does the “for” increment do?

A

increment modifies the control variable’s value, so that the loop-continuation condition eventually becomes false.

82
Q

The two semicolons in the for header?

A

are required.

83
Q

Most for statements can be represented with equivalent while statements as follows:

A
initialization;
while (loopContinuationCondition) 
{
   statements
   increment;
}
84
Q

Typically, for statements are used for ______________ iteration and while statements for ______________ iteration.

A

for statements are used for counter-controlled iteration.

while statements for sentinel-controlled iteration.

85
Q

What is true of the initialization expression if it is in the “for” header declares the control variable.

A

The control variable can be used only in that for statement—it will not exist outside the for statement.

86
Q

The expressions in a for header are

A

optional.

87
Q

The expressions in a for header are optional. If the loopContinuationCondition is omitted, Java assumes?

A

that it’s always true, thus creating an infinite loop.

88
Q

In a “for” statement

You might omit the initialization expression if?

A

the control variable is initialized before the loop.

89
Q

In a “for” statement

You might omit the increment expression if?

A

the increment is calculated with statements in the loop’s body or if no increment is needed.

90
Q

A for’s increment expression acts as if it’s a?

A

standalone statement at the end of the for’s body.

91
Q

A for statement can count downward by using a?

A

negative increment—i.e., a decrement (p. 169).

92
Q

“for” statement

What happens if the loop-continuation condition is initially false?

A

the for statement’s body does not execute.

93
Q

Java treats floating-point constants like 1000.0 and 0.05 as?

A

type double. Similarly, Java treats whole-number constants like 7 and -22 as type int.

94
Q

The format specifier %4s outputs a String in a field width (p. 172) of?

A

4 — that is, 4 character positions.

If the value to be output has fewer characters, it’s right justified (p. 172) by default. If the value has more characters, the field width expands to accommodate the appropriate number of characters. To left justify (p. 172) the value, use a negative integer to specify the field width.

95
Q

Math.pow(x, y) calculates the value of

p. 173

A

x raised to the y:th power.

The method receives two double arguments and returns a double value.

96
Q

The comma (,) formatting flag (p. 174) in a format specifier indicates that a?

A

floating-point value should be output with a grouping separator (p. 174).

The actual separator used is specific to the user’s locale (i.e., country). In the United States, the number will have commas separating every three digits and a decimal point separating the fractional part of the number, as in 1,234.45.

97
Q

The . in a format specifier indicates that?

A

the integer to its right is the number’s precision.

98
Q

What is the difference between a “while” and a “do…while” statement?

A

In the while, the program tests the loop-continuation condition at the beginning of the loop, before executing its body; if the condition is false, the body never executes.

The do…while statement tests the loop-continuation condition after executing the loop’s body; therefore, the body always executes at least once.

99
Q

A switch statement (p. 176) performs different actions based on?

A

the possible values of a constant integral expression (a constant value of type byte, short, int or char, but not long), or a String.

100
Q

The end-of-file indicator is a?

A

system-dependent keystroke combination that terminates user input.

On UNIX/Linux/macOS systems, end-of-file is entered by typing the sequence d on a line by itself. This notation means to simultaneously press both the Ctrl key and the d key.

On Windows systems, enter end-of-file by typing z.

101
Q

Scanner method hasNext (p. 179) determines whether?

A

there’s more data to input. This method returns the boolean value true if there’s more data; otherwise, it returns false. As long as the end-of-file indicator has not been typed, method hasNext will return true.

102
Q

The switch statement consists of a?

A

block that contains a sequence of case labels (p. 179) and an optional default case (p. 179).

103
Q

In a switch, the program evaluates the controlling expression and compares its value with?

A

each case label.

If a match occurs, the program executes the statements for that case.

104
Q

Listing cases consecutively with no statements between them enables the?

A

cases to perform the same set of statements.

105
Q

Every value you wish to test in a switch must be?

A

listed in a separate case label.

106
Q

Each case can have multiple statements, and these need not?

A

be placed in braces.

107
Q

A case’s statements typically end with a

A

break (p. 179) that terminates the switch’s execution.

108
Q

What happens without a “break” statement in a switch?

A

Without break statements, each time a match occurs in the switch, the statements for that case and subsequent cases execute until a break statement or the end of the switch is encountered.

109
Q

What happens if no match occurs between the controlling expression’s value and a case label?

A

the optional default case executes.

If no match occurs and the switch does not contain a default case, program control simply continues with the first statement after the switch.

110
Q

The break statement, when executed in a while, for, do…while or switch, causes?

A

immediate exit from that statement.

111
Q

What dose a continue statement (p. 182), when executed in a while, for or do…while do?

A

The continue statement (p. 182), when executed in a while, for or do…while, skips the loop’s remaining body statements and proceeds with its next iteration.

In while and do…while statements, the program evaluates the loop-continuation test immediately. In a for statement, the increment expression executes, then the program evaluates the loop-continuation test.

112
Q

Simple conditions are expressed in?

A

terms of the relational operators >, = and <= and the equality operators == and !=, and each expression tests only one condition.

113
Q

Logical operators (p. 183) enable you to?

A

form more complex conditions by combining simple conditions.

The logical operators are && (conditional AND), || (conditional OR), & (boolean logical AND), | (boolean logical inclusive OR), ^ (boolean logical exclusive OR) and ! (logical NOT).

114
Q

What do you use to ensure that two conditions are both true?

A

use the && (conditional AND) operator. If either or both of the simple conditions are false, the entire expression is false.

115
Q

What do you use to ensure that either or both of two conditions are true?

A

use the || (conditional OR) operator, which evaluates to true if either or both of its simple conditions are true.

116
Q

A condition using && or || operators (p. 185) uses short-circuit evaluation (p. 185)—they’re evaluated only?

A

until it’s known whether the condition is true or false.

117
Q

The & and | operators (p. 185) work identically to the && and || operators but?

A

always evaluate both operands.

118
Q

What do you use to ensure that the operator is true if and only if one of its operands is true and the other is false.

A

A simple condition containing the boolean logical exclusive OR (^; p. 186) operator is true if and only if one of its operands is true and the other is false.

If both operands are true or both are false, the entire condition is false. This operator is also guaranteed to evaluate both of its operands.

119
Q

What does the unary ! (logical NOT; p. 186) operator do?

A

“reverses” the value of a condition.

120
Q

Typically, __________________statements are used for counter-controlled iteration and
_______________ statements for sentinel-controlled iteration.

A

for,

while.

121
Q

The do…while statement tests the loop-continuation condition ________________ executing the loop’s body; therefore, the body always executes at least once.

A

after.

122
Q

The ___________________ statement selects among multiple actions based on the possible values
of an integer variable or expression, or a String.

A

switch.

123
Q

The _____________________ statement, when executed in an iteration statement, skips the remaining
statements in the loop body and proceeds with the next iteration of the loop.

A

continue.

124
Q

The _______________ operator (with short-circuit evaluation) can be used to ensure that two
conditions are both true before choosing a certain path of execution.

A

&& (conditional AND).

125
Q

If the loop-continuation condition in a for header is initially ______________ , the program
does not execute the for statement’s body.

A

false.

126
Q

Methods that perform common tasks and do not require objects are _______________ methods.

A

static.

127
Q

T or F

The default case is required in the switch selection statement.

A

False.

The default case is optional. If no default action is needed, then there’s no need for a default case.

128
Q

T or F

The break statement is required in the last case of a switch selection statement.

A

False.

The break statement is used to exit the switch statement. The break statement is not required for the last case in a switch statement.

129
Q

T or F

The expression ((x > y) && (a < b)) is true if either x > y is true or a < b is true.

A

False.

Both of the relational expressions must be true for the entire expression to be true when using the && operator.

130
Q

T or F

An expression containing the || operator is true if either or both of its operands are true.

A

True.

131
Q

T or F

The comma (,) formatting flag in a format specifier (e.g., %,20.2f) indicates that a value should be output with a grouping separator.

A

True.

132
Q

T or F

To test for a range of values in a switch statement, use a hyphen (–) between the start and end values of the range in a case label.

A

False.

The switch statement does not provide a mechanism for testing ranges of values, so every value that must be tested should be listed in a separate case label.

133
Q

T or F

Listing cases consecutively with no statements between them enables the cases to perform the same set of statements.

A

True.

134
Q

Write a Java statement or a set of Java statements to accomplish each of the following tasks:

Sum the odd integers between 1 and 99, using a for statement. Assume that the integer variables sum and count have been declared.

A
1 sum = 0;
2 for (count = 1; count <= 99; count += 2) {
3 sum += count;
4 }
135
Q

Write a Java statement or a set of Java statements to accomplish each of the following tasks:

b) Calculate the value of 2.5 raised to the power of 3, using the pow method.

A

double result = Math.pow(2.5, 3);

136
Q

Write a Java statement or a set of Java statements to accomplish each of the following tasks:

c) Print the integers from 1 to 20, using a while loop and the counter variable i. Assume that the variable i has been declared, but not initialized. Print only five integers per line.

[Hint: Use the calculation i % 5. When the value of this expression is 0, print a newline character; otherwise, print a tab character. Assume that this code is an application. Use the System.out.println() method to output the newline character, and use the System. out.print(‘\t’) method to output the tab character.]

A
1    i = 1;
2
3   while (i <= 20) {
4      System.out.print(i);
5
6      if (i % 5 == 0) {
7          System.out.println();
8       }
9      else {
10         System.out.print('\t');
11       }
12
13      ++i;
14  }
137
Q

Write a Java statement or a set of Java statements to accomplish each of the following tasks:

Repeat part (c), using a for statement.

A
1    for (i = 1; i <= 20; i++) {
2        System.out.print(i);
3
4        if (i % 5 == 0) {
5             System.out.println();
6        }
7         else {
8              System.out.print('\t');
9        }
10 }
138
Q

Find the error in each of the following code segments, and explain how to correct it:

1   i = 1;
2  while (i <= 10);
3        ++i;
4  }
A

Error: The semicolon after the while header causes an infinite loop, and there’s a missing
left brace.

Correction: Replace the semicolon by a {, or remove both the ; and the }.

139
Q

Find the error in each of the following code segments, and explain how to correct it:

1  for (k = 0.1; k != 1.0; k += 0.1) {
2        System.out.println(k);
3  }
A

Error: Using a floating-point number to control a for statement may not work, because floating-point numbers are represented only approximately by most computers.

Correction: Use an integer, and perform the proper calculation to get the values you desire, as in:

1  for (k = 1; k != 10; k++) {
2       System.out.println((double) k / 10);
3  }