3 Complete example code

The Stack class, depicted in Listing 1, is a fixed stack of integers and its object’s capacity is set at instantiation time. It provides push and pop operations as well as sum, which calculates the existing items in the stack.


Listing 1: The stack Class (Download from here)
 
1#include "Exception.h" 
2 
3class Stack{ 
4   private: 
5      int cap; 
6      int size; 
7      int* array; 
8   public: 
9      Stack(int = 5); 
10      ~Stack(); 
11      bool full(); 
12      bool empty(); 
13      int sum(); 
14      void push(int); 
15      int pop(); 
16   friend std::ostream &operator<<( std::ostream &, Stack const & ); 
17}; 
18 
19Stack::Stack(int c):cap(c), size(0), array(new int[cap]){} 
20 
21Stack::~Stack(){ 
22   delete[] array; 
23} 
24 
25bool Stack::full(){ 
26   return size == cap; 
27} 
28 
29bool Stack::empty(){ 
30   return size == 0; 
31} 
32 
33int Stack::sum(){ 
34   if( empty() ) 
35      throw underflow(); 
36   int result = 0; 
37   for(int i = 0; i < size; i++){ 
38      result += array[i]; 
39   } 
40   return result; 
41} 
42 
43void Stack::push(int v){ 
44   if( full()) 
45      throw overflow(); 
46   array[ ++size ] = v; 
47} 
48 
49int Stack::pop(){ 
50   if( empty() ) 
51      throw underflow(); 
52   return array[ --size ]; 
53} 
54 
55std::ostream &operator<<( std::ostream &out, Stack const &stack ) { 
56   for ( int i = 0; i < stack.size; ++i ) { 
57         out << stack.array[i] << " "; 
58   } 
59   return out; 
60}

The main method in Listing 2 provides the interactive commands to work with an instances of object. Once you run it, it asks you to enter the max cap for stack. ‘push n’ command pushes the integer ‘n’. ‘pop’ removes the top of stack and ‘print’ it on the screen. ‘sum’ calculates the item in the stack, and ‘print’ shows the items in the stack.


Listing 2: The main method instantiating an object from Stack (Download from here)
 
1#include <iostream> 
2#include <string> 
3#include "stack.h" 
4 
5using namespace std; 
6 
7int main( int argc, char *argv[] ) { 
8 
9   int input; 
10   cout << "Enter the stack size: "; 
11   cin >> input; 
12   Stack stack(input); 
13 
14   string command; 
15   do{ 
16      cout << ">"; 
17      cin >> command; 
18      if( "sum" == command ){ 
19         cout << stack.sum() << endl; 
20      }else if( "push" == command ){ 
21         int value; 
22         cin >> value; 
23         try{ 
24            stack.push(value); 
25         }catch(overflow of){ 
26            cout << "stack is full"; 
27         } 
28      }else if( "pop" == command ){ 
29         try{ 
30            cout << stack.pop() << endl; 
31         }catch(underflow of){ 
32            cout << "stack is empty" << endl; 
33         } 
34      }else if( "print" == command ){ 
35         cout << stack << endl; 
36      } 
37   }while("exit" != command); 
38 
39   cout << "Exiting.." << endl; 
40}