Show what is written by the following segment of code, given that element1, element2, and element3 are int variables, and queue is an object that fits the ADT of a queue. element1 = 1; element2 = 0; element3 = 4; queue.enqueue(element2); queue.enqueue(element1); queue.enqueue(element1 + element3); element2 = queue.dequeue( ); queue.enqueue(element3 * element3); queue.enqueue(element2); queue.enqueue(3); element1 = queue.dequeue( ); System.out.println(element1 + “ “ + element2 + “ “ + element3); while (!queue.isEmpty( )) { element1 = queue.dequeue( ); System.out.println(element1) } |
OUTPUT:
1 0 4
5
16
0
3
Explanation:
A queue is a linear data structure in which addition is done at the one end and deletion is one at another end.
Insertion can be performed at the rear end.
Deletion can be performed at the front end.
The given source code inserts the element into the queue and delete the elements from the queue and finally, the current queue is printed on the computer screen.
The statement by statement explanation of the given source code is given below:
//variable initialization
element1 = 1;
element2 = 0;
element3 = 4;
//insert the element2 = 0 into the queue
//Now the queue will be 0
queue.enqueue(element2);
//insert the element1 = 1 into the queue
//Now the queue will be 0 1
queue.enqueue(element1);
//insert the 1+4=5 into the queue
//Now the queue will be 0 1 5
queue.enqueue(element1 + element3);
//delete the first element form the queue
//Now the queue will be 1 5
//element2 = 0
element2 = queue.dequeue( );
//insert 4*4=16 into the queue
//Now the queue will be 1 5 16
queue.enqueue(element3 * element3);
//insert element2 = 0 into the queue
//Now the queue will be 1 5 16 0
queue.enqueue(element2);
//insert 3 into the queue
//Now the queue will be 1 5 16 0 3
queue.enqueue(3);
//delete the front element from the queue
//Now the queue will be 5 16 0 3
//element1 = 1
element1 = queue.dequeue( );
//display the value of element1, element2, and element3
on the computer screen
//1 0 4
System.out.println(element1 + “ “ + element2 + “ “ + element3);
//display the complete queue on the computer
screen
//5
//16
//0
//3
while (!queue.isEmpty( ))
{
element1 = queue.dequeue( );
System.out.println(element1)
}
Get Answers For Free
Most questions answered within 1 hours.