Sunday, 30 November 2014

Stack of Objects implemented in C++ [Turbo C++ version.]




Turbo C++



Graphical Representation of stack.
















Code implementation.
#include "iostream.h"
#include "conio.h"
#include "stdio.h"
const int size = 5;
class Book
{
int id;
char name[50];
public:
void getData()
{
cout << "Enter book ID: ";
cin >> id;
cout << "Enter name of the book: ";
gets(name);
}
void showData()
{
cout << "Book ID: " << id << endl;
cout << "Name of the book: "; puts(name); cout << endl;
}
};
class Stack
{
Book b_stack[size];
int top;
public:
Stack()
{
top=0;
}
void push(Book b)
{
if(!isFull())
b_stack[top++]=b;
}
Book pop()
{
if(!isEmpty())
return b_stack[--top];
}
int isFull()
{
if(top==size)
return 1;
return 0;
}
int isEmpty()
{
if(top==0)
return 1;
return 0;
}
Book peek()
{
if(!isEmpty())
return b_stack[top-1];
}
void display();
};
void Stack::display()
{
for (int i = top-1; i > -1; i--)
b_stack[i].showData();
}
void main()
{
clrscr();
Book b;
Stack s;
cout << "Enter data for Books: " << endl;
while(!s.isFull())
{
b.getData();
s.push(b);
}
b=s.peek();
cout << "Peek at the moment:\n";
b.showData();
b=s.pop();
cout << "Popped book:\n";
b.showData();
getch();
cout << "Press any key to continue.\n";
b=s.peek();
cout << "Peek after popping the top most book:\n";
b.showData();
cout << "The books in the stack at the moment are:\n";
s.display();
getch();
}
Unknown Web Developer

Morbi aliquam fringilla nisl. Pellentesque eleifend condimentum tellus, vel vulputate tortor malesuada sit amet. Aliquam vel vestibulum metus. Aenean ut mi aucto.

No comments :

Post a Comment