Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

UNIVERSITI SAINS MALAYSIA

School of Computer Sciences

Session 2016/2017, Semester 2

CPT113: Programming Methodology & Data Structures

Tutorial / Lab exercise: Stacks

1. Based on your understanding, briefly explain in your own words what is stack and
provide suitable example.

2. What are the operations of stacks, and how do they work?

3. Consider the following statement:


stackType<int> stack;
int x,y;
Show the output of the following segment of code.
x=4;
stack.push(7);
stack.push(x);
stack.push(x+5);
y=stack.top();
stack.pop();
stack.push(x+y);
stack.push(y-2);
stack.push(3);
x=stack.top();
stack.pop();
cout<<x= <<x<<endl;
cout<<y= <<y<<endl;

while(!stack.isEmptyStack())
{
cout<<stack.top()<<endl;
stack.pop();
}
4. Study the following simple program:

a. Discuss how it works?


b. Give the output.
c. Type the program and execute the program on your own.

#include<iostream>
#include<stack>
using namespace std;
void mystery(stack<int> s, stack<int>& t);
int main()
{
int list[]={5, 10, 15, 20, 25};
stack<int> s1,s2;
for (int i=0; i<5; i++)
s1.push(list[i]); //put in 0,1,2,3,4
mystery(s1,s2);
while(!s2.empty())
{
cout<<s2.top()<<" "; //display ' 0, 2, 4, 6, 8
s2.pop();
}
cout<<endl;
return 0;
}
void mystery(stack<int> s, stack<int>& t)
{
while(!s.empty())
{
t.push(2*s.top()); //push into s2 ' 8, 6, 4, 2, 0
s.pop();
}
}

Programming exercise Keep calm and do on your own

Write a program which reads a data file consisting of students' GPAs followed by their
names. The program then prints the lowest GPA and the names of the students with
the lowest GPA. The procedure of program will be similar to the programming example
on page 1142 (D.S MALIK book 6th edition).

Input: The programs read the input file namely GPAdata.txt which consists of each
student GPA and their names. (I will provide this for you)

Output: The program output the lowest GPA and the names.

Procedure: Please refer to page 1142-1146 (D.S MALIK book 6th edition, depends on
your text book edition refers to programming example: highest GPA).

You might also like