Skip to main content\(
\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 7.11 Assessment: While and For Loops
Subgoals for Evaluating a Loop.
-
-
Determine start condition
-
Determine update condition
-
Determine termination condition
-
Determine body that is repeated
-
-
For every iteration of loop, write down values
Exercises Exercises
1.
Q1: What is printed as a result of executing the following code segment?
int k = 0;
while (k < 10) {
System.out.print((k % 3) + " ");
if ((k % 3) == 0)
k = k + 2;
else
k++;
}
2.
Q2: What are the first and last numbers printed by the following code segment?
int number = 15;
while (number < 28) {
System.out.println(number);
number++;
}
3.
Q3: What is printed as a result of executing the following code segment?
int alpha = 24;
int beta = 30;
while (beta != 0) {
int rho = alpha % beta;
alpha = beta;
beta = rho;
}
System.out.println(alpha);
4.
Q4: Considering the following code, which best describes what the code does?
int var = 0;
int num = 50;
for (int x = 1; x <= num; x += 2) {
var = var + x;
}
System.out.println(var);
Prints the sum of all the integers between 1 and num, inclusive
Prints the sum of all even integers between 1 and num, inclusive
Prints the sum of all odd integers between 1 and num, inclusive
Nothing is printed, it is an infinite loop
5.
Q5: What is printed as a result of executing the following code segment?
int typeA = 0;
int typeB = 0;
int typeC = 0;
for (int k = 1; k <= 50; k++) {
if (k % 2 == 0 && k % 5 == 0)
typeA++;
if (k % 2 == 0)
typeB++;
if (k % 5 == 0)
typeC++;
}
System.out.println("%d %d %d", typeA, typeB, typeC);
You have attempted
of
activities on this page.