The following code segment is a count-controlled loop going from 1 through 5. At
ID: 669969 • Letter: T
Question
The following code segment is a count-controlled loop going from 1 through 5. At each iteration, the loop counter is either printed or put on a stack depending on the boolean result returned by the method random. [Assume that random randomly returns either true or false.] At the end of the loop, the items on the stack are removed and printed. Because of the logical properties of a stack, this code segment cannot print certain sequences of the values of the loop counter.You are given an output and asked to determinee whether the code segment could generate the output.
for ( count = 1; count <= 5; count++)
{
if (random())
System.out.println(count);
else
stack.push(count);
}
while (!stack.isEmpty());
{
number = stack.top();
stack.pop();
System.out.println(number);
}
a. The following output is possible: 1 3 5 2 4
i. True ii. False iii. Not enough information
b. The following output is possible: 1 3 5 4 2
i. True ii. False iii. Not enough information
c. The following output is possible: 1 2 3 4 5
i. True ii. False iii. Not enough information
d. The following output is possible: 5 4 3 2 1
i. True ii. False iii. Not enough information
Explanation / Answer
d)True if all the elements are pushed in to stack then it is possible the top one would be 5 and next 4 and so on.
c)True if no count is pushed in to stack then all printed diretly;
b)True possible suppose 1 3 are printed directly then 2,4 and 5 are pushed in to stack then 5 will be top element and 4 will be next and 2 at bottom so 1,3directly printed and 5,4,2 are printed through stack
a)False Not possible as 2 is coming before 4 and only way that could be possible is if printed directly but before there is 5 and 3 that not possible if 2 is printed directly so impossible
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.