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.
-
Identify loop parts
Determine start condition
Determine update condition
Determine termination condition
Determine body that is repeated
-
Trace the loop
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++;
}
0 2 1 0 2
0 2 0 2 0 2
0 2 1 0 2 1 0
0 2 0 2 0 2 0
0 1 2 1 2 1 2
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++;
}
First: 15; Last: 27
First: 15; Last: 28
First: 16; Last: 27
First: 16; Last: 28
First: 16; Last: 29
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);
0
6
12
24
30
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 value in num
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);
5 20 5
5 20 10
5 25 5
5 25 10
30 25 10
You have attempted
of
activities on this page.