In: Computer Science
Show what is written by the following segments of code, given that item1, item 2 and item 3 are int variables.
StackType stack;
item1 = 1;
item2 = 0;
item3 = 4;
stack.Push(item2);
stack.Push(item1);
stack.Push(item1 + item3);
item2 = stack.Top();
stack.Pop();
stack.Push(item3*item3);
stack.Push(item2);
stack.Push(3);
item1 = stack.Top();
stack.Pop();
cout << item1 << endl <<item2 << endl << item 3 << endl;
while (!stack.isEmpty())
{
item1 =stack.Top();
stack.Pop();
cout << item1 << endl;
}
For the given code we'll go line by line. The output that is printed by the code is given in read color.
StackType stack;
Declares an empty stack.
item1 = 1;
item2 = 0;
item3 = 4;
Declares three variables with given values.
stack.Push(item2);
Adds 0 to the stack.
stack.Push(item1);
Adds 1 to the stack.
stack.Push(item1 + item3);
Adds 1 + 4 = 5 to the stack.
item2 = stack.Top();
Changes item2 from 0 to 5.
stack.Pop();
Deletes the element at the top of the stack i.e 5;
stack.Push(item3*item3);
Adds 4*4 = 16 to the stack.
stack.Push(item2);
Adds 5 to the stack.
stack.Push(3);
Adds 3 to the stack.
item1 = stack.Top();
Changes item1 from 1 to 3.
stack.Pop();
Deletes the element at the top of the stack i.e 3.
cout << item1 << endl <<item2 << endl << item 3 << endl;
Prints to the screen the values:
3
5
4
while (!stack.isEmpty())
{
item1 =stack.Top();
stack.Pop();
cout << item1 << endl;
}
Till the time stack is not empty, assign the item at the top of the stack to item1, delete the item at the top of the stack and print item1.
So this loop will print the entire stack from top to bottom. Here's its output:
5
16
1
0