Computer Science Questions.
Computer Science Questions.
What output is generated by this for loop?
for (int i = 1; i <= 50; i = i * 2)
System.out.println(i);
No output is generated.
1, 2, 4, 8, 16
2, 4, 8, 16, 32
1, 2, 4, 8, 16, 32
Question 2
Which for loop header has symmetric bounds?
for (i = 1; i <= n; i++)
for (i = 10; i < 40; i += 5)
for (i = a; i < b; i++)
for (i = 0; i < str.length(); i++)
Question 3
What is the purpose of the following algorithm?
(In other words, what does this code do?)
boolean found = false;
int i = str.length() – 1;
while (!found && i > 0)
{
ch = str.charAt(i);
if (ch == ‘-‘) { found = true; }
else { i–; }
}
counting matches
comparing adjacent values
finding the last match
prompting until a match is found
Question 4
Which statement completes this investment loop?
for (years = 1;
(balance = balance + balance * rate / 100) < targetBalance;
years++)
__________
:
;
balance++;
years–;
Question 5
Which for loop is equivalent to the given while loop?
i = 1;
while (i <= 5)
{
. . .
i++;
}
for (i = 1; i < 5; i++) { … }
for (i = 1; i >= 5; i++) { … }
for (i = 1; i <= 5; i++) { … }
for (i = 1; i != 5; i++) { … }
Question 6
Consider the following pseudocode for dealing cards to players in a card game:
For the required number of cards
For the required number of players
Deal a card.
Which statement corresponds to the outer loop of the pseudocode?
for (int players=1; players < NUMBER_OF_PLAYERS; players++)
- for (int cards=1; cards <= NUMBER_OF_CARDS; cards++)
- for (int cards=1; cards < NUMBER_OF_CARDS; cards++)
- for (int players=1; players <= NUMBER_OF_PLAYERS; players++)
Question 7
What output does this for loop generate?
for (int i = 1; i <= 5; i++)
{
System.out.print(i + ” “);
}
System.out.println(i + 1);
1 2 3 4 5
The output is infinite.
None because the code does not compile.
1 2 3 4 5 6
Question 8
What term is used to represent a value that indicates the end of a data set?
finite
sentinel
end
fence
Question 9
Fill in the missing for loop header to compute pow(a, n).
int power = 1;
for ___________________
power = power * a;
(int f = 1; f < n; f++)
(int p = 1; p < n; p++)
(int f = n; f > 1; f–)
(int p = 1; p <= n; p++)
Question 10
Fill in the missing for loop header to compute n! (n factorial). The factorial of a number n is the product n * (n – 1) * … * 2 * 1.
int factorial = 1;
for ___________________
factorial = factorial * f;
(int f = 1; f < n; f++)
(int i = 1; i <= n; i++)
(int i = n; i > 0; i–)
(int f = n; f > 0; f–)
Is this the question you were looking for? If so, place your order here to get started!