View
218
Download
2
Category
Preview:
Citation preview
S.E Computer (First Semester) Examination 2017
OBJECT ORIENTED PROGRAMMING
(2015 Pattern)
Apr / May 2017
Time : 2 Hours Maximum Marks : 50
Q.1 a) Explain friend function with example. [4]
Ans
C++ friend functions are special functions which can access the private members of
a class.
it is different from a normal function : In a normal function, a member is “access”
through the “object” Ex : sample object; object.getdata( );
Whereas a friend function requires object to be passed by value or by reference as a
parameter Ex : sample object; getdata(object) ;
Syntax:
class class_name
{
//class definition
public:
friend rdt fun_name(formal parameters);
};
Example :
class demo
{
int x ;
public :
demo(int xxx)
{
x = xxx;
}
friend void display(demo) ;
};
void display(demo d1)
{
cout<<dd1.x;
}
int main( )
{
demo d(5);
display(d);
return 0;
}
Q.1 b) Consider the following declaration
class TRAIN
{
int trainno;
char dest[20];
float distance;
public :
void get(); // To read an object from the keyboard
void put(); // To write an object into a file
void show(); //To display the file contents on the monitor
};
Complete the member functions definition [8]
Ans.
void TRAIN::get()
{
cout <<”\nEnter trainno , its destination and distance from source : “;
cin >> trainno;
gets(dest);
cin>>distance;
}
void TRAIN::put()
{
fstream File;
File.open( “STOCK.DAT”, ios::binary | ios::in | ios::out);
File.write( (char*)this, sizeof(this));
File.close();
}
void TRAIN::show()
{
fstream File;
File.open( “STOCK.DAT”, ios::binary | ios::in);
File.read((char*)this, sizeof(this));
cout << trainno << ”==> ” << dest << “==> “ <<distance<<endl;
File.close();
}
Or
Q.2 a) List the features of Object Oriented Programming. [3]
Ans
FEATURES OF OOP:
1) Object
2) Class
3) Encapsulation
4) Abstraction
5) Dynamic Binding
6) Message Passing
7) Inheritance
8) Polymorphism
Q.2 b) What is Pointer, Smart Pointer and Shared Pointer. Explain using diagram and
program 9M
Ans.
Pointer
A Pointer is just an address of the data stored in memory. Consider the below code:
int var = 1;
int main()
{
int num = 10;
printf("Value of var is: %d", num);
printf("Address of var is: %u", &num);
return 0;
}
Output:
Value of var is: 10
Address of var is: 00XBBA77
So let’s say computer assigned a location 00XBBA77 for variable num, which means whatever value we would be assigning to num should be stored at location: 00XBBA77. As shown in Figure.
Smart Pointer
(i) Smart pointers are class objects that behave like built-in pointers but also manage
objects that you create with new so that you don't have to worry about when and
whether to delete them.
(ii) The smart pointers automatically delete the managed object at the appropriate time.
(iii) The objects of smart pointer class look like pointer, but can do many things that a
normal pointer can’t like automatic destruction, reference counting and more.
Example for Smart Pointers
#include<iostream>
using namespace std;
class SmartPtr
{
int *ptr; // Actual pointer
public:
// Constructor
explicit SmartPtr(int *p = NULL)
{
ptr = p;
}
// Destructor
~SmartPtr()
{
delete(ptr);
}
// Overloading dereferencing operator
int &operator *()
{
return *ptr;
}
int *operator ->() //Overloading Access operator
{
return ptr;
}
};
int main()
{
SmartPtr ptr(new int());
*ptr = 20;
cout << *ptr;
return 0;
}
We don't need to call delete ptr: when the object ptr goes out of scope, destructor for it is
automatically called and destructor does delete ptr.
Shared Pointer
(i) Shared_ptr is a container for a raw pointer.
(ii) It maintains reference counting ownership of its contained pointer in cooperation
with all copies of the shared_ptr.
(iii) An object referenced by the contained raw pointer will be destroyed when and only
when all copies of the shared_ptr have been destroyed.
(iv) The shared_ptr class template is a referenced-counted smart pointer; a count is
kept of how many smart pointers are pointing to the managed object; when the last
smart pointer is destroyed, the count goes to zero, and the managed object is then
automatically deleted.
(v) It is called a "shared" smart pointer because the smart pointers all share ownership
of the managed object - any one of the smart pointers can keep the object in
existence;
(vi) Using these can simplify memory management, as shown with a little example
diagrammed below:
Suppose we need two containers (A and B) of pointers referring to a single set of objects,
X1 through X3.
Now, Suppose that if we remove the pointer to one of the objects from one of the
containers, we will want to keep the object if the pointer to it is still in the other container,
but delete it if not.
Suppose further that at some point we will need to empty container A or B, and only when
both are emptied, we will want to delete the three pointed-to objects.
Suppose further that it is hard to predict in what order we will do any of these operations
Instead of writing some delicate code to keep track of all the possibilities, we could use
smart pointers in the containers instead of built-in pointers.
Then all we have to do is simply remove a pointer from a container whenever we want, and
if it turns out to be the last pointer to an object, it will get "automatically" deleted. Likewise,
we could clear a container whenever we want, and if it has the last pointers to the objects,
then they all get deleted.
Q.3 a) What is exception handling? [3M]
Ans. An exception is a problem that arises during the execution of a program. A C++ exception
is a response to an exceptional circumstance that arises while a program is running, such as
an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.
throw: A program throws an exception when a problem shows up. This is done
using a throw keyword.
catch: A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception.
try: A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.
ptr
ptr
ptr
ptr
ptr
ptr
X1 X2
X3
Assuming a block will raise an exception, a method catches an exception using a
combination of the try and catch keywords. A try/catch block is placed around the code
that might generate an exception.
Program :
void main()
{
int no1, no2;
try
{
cout << “Enter two nos:”;
cin >> no1 >> no2;
if (no2 == 0)
throw “Divide by zero”;
else
throw no1/no2;
}
catch (char *s)
{
cout << s;
}
catch (int ans)
{
cout << ans;
}
}
- We know that divide by zero is an exception. If user enters second no as zero, the program
throws an exception, which is caught and an error message is printed else the answer is
printed.
Q.3 b) Explain :
(i) Virtual base class
(ii) Abstract class [4M]
Ans.
(i) Virtual Base Class
An ambiguity can arise when several paths exist to a class from the same base class. This
means that a child class could have duplicate sets of members inherited from a single
base class.
C++ solves this issue by introducing a virtual base class. When a class is made virtual,
necessary care is taken so that the duplication is avoided regardless of the number of
paths that exist to the child class.
When two or more objects are derived from a common base class, we can prevent
multiple copies of the base class being present in an object derived from those objects
by declaring the base class as virtual when it is being inherited. Such a base class is
known as virtual base class. This can be achieved by preceding the base class’ name
with the word virtual.
Consider the following example :
class A
{
public:
int i;
};
class B : virtual public A
{
public:
int j;
};
class C: virtual public A
{
public:
int k;
};
class D: public B, public C
{
public:
int sum;
};
int main()
{
D ob;
ob.i = 10; //unambiguous since only one copy of i is inherited.
ob.j = 20;
ob.k = 30;
ob.sum = ob.i + ob.j + ob.k;
cout << “Value of i is : ”<< ob.i<<”\n”;
cout << “Value of j is : ”<< ob.j<<”\n”; cout << “Value of k is :”<< ob.k<<”\n”;
cout << “Sum is : ”<< ob.sum <<”\n”;
return 0;
}
(ii) Abstract Class
Abstract class in C++ programming is a class that contains at least one pure virtual
function. (Pure virtual function in C++ is a virtual functions with no implementation). It
may also contain non-virtual functions and member variables. Pure virtual functions in
abstract class is implemented by its derived classes.
Main important point of an abstract class is that we cannot create an object of it, but we
create a pointer. And, in this pointer, we assign the object of derived classes.
/Abstract base class
class AbstractBase
{
public:
virtual void Display() = 0; //Pure Virtual Function declaration
};
//Derived class that will inherit the abstract base class
// and implement pure virtual function.
class Derived:public AbstractBase
{
public:
void Display()
{
cout << "pure virtual function implementation"; }
};
//-------------- TEST-Abstract Class ---------------
int main() {
AbstractBase *basePointer = new Derived(); basePointer->Display();
// OR
AbstractBase * bPtr;
Derived dObj;
bPtr = &dObj;
bPtr->Display();
//Abstract base class object can't be created.
//AbstractBase obj; // Compiler will flash an error.
}
Q.3 c) What is generic programming ? How it is implemented in C++? [5M]
Ans.
Generic programming means : not writing source code that is compiled as-is but to
write “templates” of source codes that the compiler in the process of compilation
transforms into source codes.
The simplest example for generic programming are container classes like arrays,
lists or maps that contain a collection of other objects.
Generic programming is basically the idea that your code should be generic as
possible.
It is implementing the concept that make the program generalize means works for
any data type or data structure .
In the context of C++ (and called meta programming) it means to write programs
that are evaluated at compile time.
In C++ it can be done with the help of templates.
For Ex:
#include<iostream> using namespace std; template<class T1> void disp(T1 a) { cout<<a<<endl; } int main() { disp(500); disp(9.8); disp(‘h’); return 0; }
Or Q.4 a) Explain class template using multiple parameters. Write a program in C++
[8M]
Ans. Class Template
1) Similar to functions classes can also be declared to handle different data types. Such
classes are known as class templates.
2) These classes are of generic type, and member functions of these classes can operate
on different data types.
3) The class template may contain one or more parameters of generic data type. The
arguments are separated by commas with a template declaration.
4) The declaration is as follows:
template <class T1,class T2>
class class-name {
//class declarations and definitions.
}
Here, T1 and T2 are the placeholder type name, which will be specified when a class
is instantiated.
Program :
#include<iostream.h>
#include<conio.h>
template <class T1,class T2>
class data
{ public :
data (T1 a, T2 b)
{
cout<<”\na= “ <<a<<”b=”<<b;
}
int main()
{
clrscr();
data<int,float> h(2,2.5);
data<int,char> i(15,’C’);
data<float,int> j(3.12,50);
return 0;
}
OUTPUT : a=2 b=2.5
a=15 b=C
a=3.12 b=50
Q.4 b) Explain significance of static keyword in programming? [4M]
Ans
1) Static is a keyword in C++ used to give special characteristics to an element. Static
elements are allocated storage only once in a program lifetime in static storage area.
2) They have a scope till the program lifetime.
3) Static Keyword can be used with following,
Static variable in functions : Static variables when used inside function are
initialized only once, and then they hold there value even through function
calls.
Static Class Objects : Objects declared static are allocated storage in static
storage area, and have scope till the end of program.
Static member Variable in class : Static data member has a single piece of
storage, and is not available as separate copy with each object, like other
non-static data members.
Static Methods in class : Can be called using an object and the direct member
access . operator. But, its more typical to call a static member function by
itself, using class name and scope resolution:: operator.
Q.5 a) Write the C++ file input and output program using seekg() , tellg() and read( )
etc member functions. [7M]
Ans
// using the seekg(), tellg(), open(), read(), fail() etc
#include <iostream>
#include <fstream>
using namespace std;
void main(void)
{
char filename[ ] = "C:\\testfileio.txt";
fstream inputfile, outputfile;
int length;
char* buffer;
// create, open and write data to file
outputfile.open(filename, ios::out);
// simple error handling
if(inputfile.fail())
{
cerr<<"The file "<<filename<<" could not be created/opened!\n";
exit(1);
}
// test if successful to close the file
else
cout<<"The "<<filename<<" file was opened successfully!\n";
// write some text
cout<<"Writing some text to the output file..."<<endl;
outputfile<<"This is just line of text as a simple file content. This is testfileio.txt file"<<endl;
// close the output file
cout<<"Closing the output file..."<<endl;
outputfile.close();
// opening and reading data from file
cout<<"Opening the input file..."<<endl;
inputfile.open(filename, ios::in);
// simple error handling for files creating/opening for writing
if(inputfile.fail())
{
cout<<"Opening "<<filename<<" file for reading\n";
cout<<"------------------------------------------\n";
cerr<<"The file "<<filename<<" could not be created/opened!\n";
cerr<<"Possible errors:\n";
cerr<<"1. The file does not exist.\n";
cerr<<"2. The path was not found.\n";
exit(1); // just exit
// 0-normal, non zero - some errors
}
else
{
cout<<"The "<<filename<<" file was opened successfully!\n";
cout<<"\nMove the pointer to the end\n"
<<"Then back to the beginning with\n"
<<"10 offset. The pointer now at...\n"<<endl;
// flush the stream buffer explicitly
cout<<flush;
// get length of file, move the get pointer to the end of the stream
inputfile.seekg(0, ios::end);
// The tellg() member function returns the current stream position.
length = inputfile.tellg();
cout<<"string length = "<<length<<"\n";
// dynamically allocate some memory storage for type char
buffer = new char[length];
// move back the pointer to the beginning with offset of 10 (skips 10 char)
inputfile.seekg(10, ios::beg);
// read data as block from input file
inputfile.read(buffer, length);
cout<<buffer<<endl;
// free up the allocated memory storage
delete [ ] buffer;
// close the input file
inputfile.close();
}
return;
}
Output example:
The C:\\testfileio.txt file was opened successfully!
Writing some text to the output file...
Closing the output file...
Opening the input file...
The C:\\testfileio.txt file was opened successfully!
Move the pointer to the end
Then back to the beginning with
10 offset. The pointer now at...
string length = 82
Q.5 b) What are cin and cout? Explain iostream. [6M]
Ans
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a
keyboard, a disk drive, or a network connection etc. to main memory, this is called input
operation and if bytes flow from main memory to a device like a display screen, a printer, a
disk drive, or a network connection, etc, this is called output operation.
The standard output stream (cout)
1. The predefined object cout is an instance of ostream class.
2. The cout object is said to be "connected to" the standard output device, which
usually is the display screen.
3. The cout is used in conjunction with the stream insertion operator, which is
written as << which are two less than signs as shown in the following example.
The standard input stream (cin)
The predefined object cin is an instance of istream class. The cin object is said to be
attached to the standard input device, which usually is the keyboard. The cin is used in
conjunction with the stream extraction operator, which is written as >> which are two
greater than signs as shown in the following example.
#include <iostream>
using namespace std;
int main( ) {
char name[50];
cout << "Please enter your name: ";
cin >> name;
cout << "Your name is: " << name << endl;
}
When the above code is compiled and executed, it will prompt you to enter a name. You
enter a value and then hit enter to see the result something as follows:
Please enter your name: cplusplus
Your name is: cplusplus
Iostream
1. <iostream> to C++ is basically what <stdio.h> is to C.
2. iostream - header is used to access the input output built in functions of the
language as it is the the “Standard input/output streams library”.
3. Here input-output refers to the fact of taking input command and showing output
result in the program.
4. “cin>>” , “cout<<” - these are the member objects of the <iostream> header.
Or
Q.6 a) What are various functions which are used to manipulate file pointers?
Explain using example 7M
Ans.
A file pointer is used to navigate through a file. We can control this movement of the file
pointer by ourselves. The file stream class supports the following functions to manage such
situations.
• seekg ():moves get pointer (input) to a specified location.
• seekp ():moves put pointer (output) to a specified location.
• tellg ():gives the current position of the get pointer.
• tellp (): gives the current position of the put pointer.
The other prototype for these functions is:
seekg(offset, refposition );
seekp(offset, refposition );
The parameter offset represents the number of bytes the file pointer is to be moved from
the location specified by the parameter refposition. The refposition takes one of the
following three constants defined in the ios class.
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file
example:
file.seekg(-10, ios::cur);
Example
#include<iostream>
#include<fstream>
struct record
{
char code[6];
char name[20];
int i;
}r;
int main()
{
fstream file("Temp.dat",std::ios::trunc|std::ios::in|std::ios::out|std::ios::binary);
if(!file)
{
std::cout<<"unable to open file";
exit(0);
}
cout<<"enter character code, name and an int\n";
cin.getline(r.code,6);
cin.getline(r.name,20);
cin>>r.i;
file.write((char *)&r,sizeof(r));
std::cout<<"\n\n"<<file.tellg()<<'\n'<<file.tellp();
file.seekg(3);
std::cout<<"\n\n"<<file.tellg()<<'\n'<<file.tellp();
file.seekp(5);
std::cout<<"\n\n"<<file.tellg()<<'\n'<<file.tellp();
file.seekg(3,ios::cur);
std::cout<<"\n\n"<<file.tellg()<<'\n'<<file.tellp();
file.seekp(-5,ios::end);
std::cout<<"\n\n"<<file.tellg()<<'\n'<<file.tellp();
}
Q.6 b) Explain command line arguments in C++? Write program to explain the same.
[6]
Ans If any input value is passed through command prompt at the time of running of
program is known as command line argument. It is a concept to passing the arguments to
the main() function by using command prompt.
Command line arguments application main() function will takes two arguments that is;
argc
argv
(i) argc: argc is an integer type variable and it holds total number of arguments which is
passed into main function. It take Number of arguments in the command line including
program name.
(ii) argv[]: argv[] is a char* type variable, which holds actual arguments which is passed to
main function.
Command line arguments are not compile and run like normal C++ programs, these
programs are compile and run on command prompt. To Compile and Link Command Line
Program we need TCC Command.
(i) First open command prompt
(ii) Follow the directory where code is saved.
(iii) For compile -> C:/TC/BIN>TCC mycmd.cpp
(iv) For run -> C:/TC/BIN>mycmd 10 20
#include<iostream.h>
#include<conio.h>
void main(int argc, char* argv[])
{
int i;
clrscr();
cout<<"Total number of arguments: "<<argc;
for(i=0;i< argc;i++)
{
cout<<endl<< i;<<"argument: "<<argv[i];
getch();
}
Output
C:/TC/BIN>TCC mycmd.cpp
C:/TC/BIN>mycmd 10 20
Number of Arguments: 3
0 arguments c:/tc/bin/mycmd.exe
1 arguments: 10
2 arguments: 20
Q.7 a) Use minimum 8 functions of vector STL. Write a program to explain the
same. [7]
Ans Vectors are sequence containers which represent arrays which can change in size. Thus,
we need not specify its length at the time of declaration and can change it later in the
program.
1. size() function returns the length (i.e. number of elements in the vector).
2. at() function is used to access the element at specified position (index).
3. The front() function returns the first element of a vector.
4. back() function returns the last element of a vector.
5. empty() function checks whether a vector contains any element or not. It returns 1
if the length of a vector is 0 and 0 if it contains some element.
6. resize() function resizes a vector so that it contains the specified number of
elements.
7. push_back() function adds a new element at the end of the vector (at the end of the
last element of the vector), thus increasing the size of the vector by one.
8. capacity() function returns the storage space allocated for the vector. In other
words, it returns the number of elements which can be stored in the storage space
allocated for the vector. Vector capacity is always greater than or equal to the vector
size.
9. insert() function inserts a new element in a vector before the element at the
specified position.
10. clear() removes all elements of a vector.
11. erase() function removes either a single element or a range of elements from a
vector.
#include <iostream>
#include <vector>
#include <iterator>
int main()
{
vector<int> marks = {50, 45, 47, 65, 80};
vector<int> vtest;
cout << "length of array : " << marks.size() << std::endl;
marks = {50, 47, 60};
cout << "length of array : " << marks.size() << std::endl;
cout << "marks[" << 2 << "] = " << marks.at(2) << endl;
cout << marks.front() << endl;
cout << marks.back() << endl;
cout<<”The output following if 1 vector is empty and 0 vector is not empty”<<endl;
cout << “Marks vector empty : “ <<marks.empty() << endl;
cout << “vtest vector empty : “ <<vtest.empty() << endl;
marks.resize(5);
cout << "length of array : " << marks.size() << std::endl;
marks.push_back(87);
cout << "elements of marks" << endl;
for(int i = 0; i < marks.size(); i++)
{
cout << marks[i] << endl;
}
marks.capacity();
iterator it = marks.begin();
marks.insert(it,20);
for(int i = 0; i < marks.size(); i++)
cout << marks[i] << endl;
it = marks.begin();
marks.insert(it+4, marks.begin(), marks.end());
for(int i = 0; i < marks.size(); i++)
cout << marks[i] << endl;
marks.erase(marks.begin()+4); // removing a single element at position 4
for(int i = 0; i < marks.size(); i++)
cout << marks[i] << endl;
marks.erase(marks.begin()+1, marks.begin()+2); // removing range of elements from
//position 1 till 2
marks.clear();
return 0;
}
Q.7 b) What is STL? List different types of STL Containers? [6]
Ans
The C++ STL (Standard Template Library) is a powerful set of C++ template classes to
provide general-purpose templatized classes and functions that implement many popular
and commonly used algorithms and data structures like vectors, lists, queues, and stacks.
Core of the C++ Standard Template Library are following three well-structured
components:
Component Description
Containers
Containers are used to manage collections of objects of a certain
kind. There are several different types of containers like deque,
list, vector, map etc.
Algorithms
Algorithms act on containers. They provide the means by which
you will perform initialization, sorting, searching, and
transforming of the contents of containers.
Iterators
Iterators are used to step through the elements of collections of
objects. These collections may be containers or subsets of
containers.
The STL contains many different container classes that can be used in different situations.
Generally speaking, the container classes fall into three basic categories: Sequence
containers, Associative containers, and Container adapters. In Total, STL Defines 10
Containers.
• Sequence
1. vector
2. deque
3. list
• Associative
1. set
2. multiset
3. map
4. multimap
• Derived
1. stack
2. queue
3. Priority_queue
Or Q.8 a) Write a program to implement Map using STL. [6]
Ans
Here is source code of the C++ Program to demonstrate Map in Stl.
/*
* C++ Program to Implement Map in Stl
*/
#include <iostream>
#include <map>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
map<char,int> mp;
map<char, int>::iterator it;
int choice, item;
char s;
while (1)
{
cout<<"\n---------------------"<<endl;
cout<<"Map Implementation in Stl"<<endl;
cout<<"\n---------------------"<<endl;
cout<<"1.Insert Element into the Map"<<endl;
cout<<"2.Delete Element of the Map"<<endl;
cout<<"3.Size of the Map"<<endl;
cout<<"4.Find Element at a key in Map"<<endl;
cout<<"5.Dislplay by Iterator"<<endl;
cout<<"6.Count Elements at a specific key"<<endl;
cout<<"7.Exit"<<endl;
cout<<"Enter your Choice: ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter value to be inserted: ";
cin>>item;
cout<<"Enter the key: ";
cin>>s;
mp.insert(pair<char,int>(s ,item));
break;
case 2:
cout<<"Enter the mapped string to be deleted: ";
cin>>s;
mp.erase(s);
break;
case 3:
cout<<"Size of Map: ";
cout<<mp.size()<<endl;
break;
case 4:
cout<<"Enter the key at which value to be found: ";
cin>>s;
if (mp.count(s) != 0)
cout<<mp.find(s)->second<<endl;
else
cout<<"No Element Found"<<endl;
break;
case 5:
cout<<"Displaying Map by Iterator: ";
for (it = mp.begin(); it != mp.end(); it++)
{
cout << (*it).first << ": " << (*it).second << endl;
}
break;
case 6:
cout<<"Enter the key at which number of values to be counted: ";
cin>>s;
cout<<mp.count(s)<<endl;
break;
case 7:
exit(1);
break;
default:
cout<<"Wrong Choice"<<endl;
}
}
return 0;
}
Q.8 b) What is container? List the Container classes in C++. Explain any one of them
using program? [7]
Ans
Containers are used to manage collections of objects of a certain kind. A container class
describes an object that holds other objects.There are several different types of containers
like deque, list, vector, map etc.
Container Classes :
1. vector
2. deque
3. list
4. set
5. multiset
6. map
7. multimap
8. stack
9. queue
10. priority_queue
Stacks are a type of container adaptor, specifically designed to operate in a LIFO context
(last-in first-out), where elements are inserted and extracted only from one end of the
container.
Stacks are implemented as containers adaptors, which are classes that use an encapsulated
object of a specific container class as its underlying container, providing a specific set of
member functions to access its elements. Elements are pushed/popped from the "back" of
the specific container, which is known as the top of the stack.
The container shall support the following operations:
empty
size
back
push_back
pop_back
#include <iostream> #include <stack> #include <string> #include <cstdlib> using namespace std; int main() { stack<int> st; int choice, item; while (1) { cout<<"\n---------------------"<<endl; cout<<"Stack Implementation in Stl"<<endl; cout<<"\n---------------------"<<endl; cout<<"1.Insert Element into the Stack"<<endl; cout<<"2.Delete Element from the Stack"<<endl; cout<<"3.Size of the Stack"<<endl; cout<<"4.Top Element of the Stack"<<endl; cout<<"5.Exit"<<endl; cout<<"Enter your Choice: "; cin>>choice; switch(choice) { case 1: cout<<"Enter value to be inserted: "; cin>>item; st.push(item); break;
case 2: item = st.top(); st.pop(); cout<<"Element "<<item<<" Deleted"<<endl; break; case 3: cout<<"Size of the Queue: "; cout<<st.size()<<endl; break; case 4: cout<<"Top Element of the Stack: "; cout<<st.top()<<endl; break; case 5: exit(1); break; default: cout<<"Wrong Choice"<<endl; } } return 0; }
Recommended