Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lab 5 fl23733

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

National University of Modern Languages

Islamabad

Submitted by: SYEDA ALISHAH


Submitted to: MAM MARIYAM IMTIAZ
Course: DSA
Roll Number: FL23733
LAB 5
1. Write a C++ Program that creates a template class with two functions. One
function take input from user and other function displays the number. You
are required to create this template class for integer and floating-point
values.

#include <iostream>
using namespace std;
template <class type>
class input {
private:
type a;
public:
input();
void show();
};
template <class type>
input<type>::input() {
cout << "Enter a number: ";
cin >> a;
}
template <class type>
void input<type>::show()
{
cout << "The number you entered is: " << a << endl;
}
int main() {
input<int> Obj1;
Obj1.show();
input<float> Obj2;
Obj2.show();

return 0;
}
2. You are required to implement following operations of Stack using array in C++.
Push
Pop
Top
IsEmpty
IsFull
Your Stack class should have a constructor and destructor. The program should also
contain
the main function which calls the stack operations and display the values in stack

#include <iostream>

using namespace std;

template<class ItemType>

class StackType {

public:

StackType(int size);

~StackType();

bool IsEmpty() const;

bool IsFull() const;

ItemType Top() const;

void Push(ItemType newItem);

void Pop();
private:

int top;

int maxStack;

ItemType* items;

};

template<class ItemType>

StackType<ItemType>::StackType(int size) {

top = -1;

maxStack = size;

items = new ItemType[maxStack];

template<class ItemType>

StackType<ItemType>::~StackType() {

delete[] items;

template<class ItemType>

bool StackType<ItemType>::IsEmpty() const {

return (top == -1);

template<class ItemType>

bool StackType<ItemType>::IsFull() const {

return (top == maxStack - 1);

template<class ItemType>

ItemType StackType<ItemType>::Top() const

{
return items[top];

template<class ItemType>

void StackType<ItemType>::Push(ItemType newItem)

top++;

items[top] = newItem;

template<class ItemType>

void StackType<ItemType>::Pop()

top--;

int main() {

StackType<int> stack(5);

int values[5];

for (int i = 0; i < 5; i++) {

if (!stack.IsFull()) {

cout << "Enter a value to push: ";

cin >> values[i];

stack.Push(values[i]);

cout << "Top item: " << stack.Top() << endl;

}
}

cout << "Popping all values from the stack..." << endl;

while (!stack.IsEmpty()) {

cout << "Popping: " << stack.Top() << endl;

stack.Pop();

if (!stack.IsEmpty()) {

cout << "New top after pop: " << stack.Top() << endl;

else {

cout << "Stack is now empty." << endl;

return 0;

You might also like