Skip to main content
Contents
Dark Mode Prev Up Next Scratch ActiveCode Profile
\(
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section 8.4 Assessment: Writing Loops
Subgoals for Writing a Loop.
Determine purpose of loop
Pick a loop structure (while, for, do_while)
Define and initialize variables
Determine termination condition
Invert termination condition to continuation condition
Update loop control variable to reach termination
Exercises Exercises
1.
Q1: Given the following code segment:
int x = 1;
while ( /* condition */ ) {
if (x % 2 == 0) {
System.out.print(x + " ");
}
x = x + 2;
}
Consider the following conditions to replace
/* condition */
in the code segment:
For which of the conditions will nothing be printed?
2.
Q2: Given the following code segment which is intended to print the number of integers that evenly divide the integer inputVal. You may assume that inputVal > 0. Which of the following can be used to replace /* condition */ so that numDivisors will work as intended?
int count = 0;
int inputVal = /* user entered value */
for (int k = 1; k <= inputVal; k++) {
if ( /* condition */ ) {
count++;
}
} // end for
System.out.println(count);
3.
Q3: Which of the following code segments will produce the output:
int k = 1;
while (k < 20) {
if (k % 3 == 1)
System.out.print(k + " ");
k = k + 3;
}
for (int k = 1; k < 20; k++) {
if (k % 3 == 1)
System.out.print(k + " ");
}
for (int k = 1; k < 20; k = k + 3) {
System.out.print(k + " ");
}
4.
Q4: What is the maximum number of times βHelloβ can be printed?
int k = // a random number such that 1 <= k <= n ;
for (int p = 2; p <= k; p++) {
for (int r = 1; r < k; r++)
System.out.println("Hello");
}
You have attempted
of
activities on this page.