Show what is written by the following segments of code, given item1, item2, and
ID: 669962 • Letter: S
Question
Show what is written by the following segments of code, given item1, item2, and item3 are int variables, and stack is an object that fits the abstract description of a stack as given in the section. Assume that you can .... and retrieve variables of type int on stack.
a. item = 1;
item2 = 0;
item3 = 4;
stack.push(item2);
stack.push(item1);
stack.push(item1 + item3);
item2 = stack.top();
stack.push (item3 * item3);
stack.push (item2);
stack.push(3);
item1 = stack.top();
stack.pop();
System.out.println(item1 + " " + item2 + " " + item3);
while (!stack.isEmpty())
{
item1 = stack.top();
stack.pop();
System.out.println(item1);
}
b. item1 = 4;
item3 = 0;
item2 = item1 + 1;
stack.push(item2);
stack.push(item2 + item1);
stack.push(item1);
item2 = stack.top();
stack.pop();
item1 = item2 + 1;
stack.push(item1);
stack.push(item3);
while (!stack.isEmpty())
{
item3 = stack.top();
stack.pop();
System.out.println(item3);
}
System.out.println(item1 + " " + item2 + " " + item3);
Explanation / Answer
1) item = 1; //Declare a variable int
item2 = 0; //Declare a variable int
item3 = 4; //Declare a variable int
stack.push(item2); //Push item2 to the stack
stack.push(item1); //Push item1 to the stack
stack.push(item1 + item3); //Push sum of item1 & item2 to the stack
item2 = stack.top(); //observe top of the stack (sum of item1 & item2 will be assigned to item2)
stack.push (item3 * item3); //Push square of item3 to the stack
stack.push (item2); //Push item2 to the stack
stack.push(3); //Push 3 to the stack
item1 = stack.top(); //observe top of the stack (3 will be assigned to item1)
stack.pop(); //3 will be popped from stack
System.out.println(item1 + " " + item2 + " " + item3); // 3 5 4 will be printed
//Stack will be printed
while (!stack.isEmpty())
{
item1 = stack.top();
stack.pop();
System.out.println(item1);
}
OP — 5 16 5 1 0
2)
item1 = 4;
item3 = 0;
item2 = item1 + 1;
stack.push(item2); //Push item2 to the stack
stack.push(item2 + item1); //Push item2 & item1 to the stack
stack.push(item1); //Push item1 to the stack
item2 = stack.top(); //item2 is assigned with value of item1
stack.pop(); //item2 is popped off
item1 = item2 + 1; //item1 is incremented with the value of item2+1
stack.push(item1); //item1 is pushed
stack.push(item3); //item3 is pushed
//print the stack
while (!stack.isEmpty())
{
item3 = stack.top();
stack.pop();
System.out.println(item3);
}
//OP — 0 5 9 5
System.out.println(item1 + " " + item2 + " " + item3); // 5 4 5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.