Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. Create a new method on a Stack that determines if all the values on the Stack

ID: 3685689 • Letter: 1

Question

1. Create a new method on a Stack that determines if all the values on the Stack are smaller than the passed value. For example, for a stack containing top- (1) (1) (2) (3) (5) (5) (2), allSmaller( 3 ) should return false because there values on the Stack bigger than 3. On the other hand, for a stack containing top- (1) (1) (2) (3) (5) (5) (2), allSmaller( 12 ) should return true because all the values on the stack are less than 12.

This new operation should have the signature:

bool Stack<Object>::allSmaller( const Object & data ) const;

Because it has been marked const, this method is saying that it is read-only. When your implementation runs, you won't be able to actually change any data members of the Stack passed to your method. Create a test driver program that exercises each of these exercises to satisfy yourself that your implementation is correct. For example, you should print the Stack before and after invoking the operation.

2. Create a new method on a Stack that determines if how many times a passed value is found on the Stack. For example, for a stack containing top- (1) (1) (2) (3) (5) (5) (2), count( 3 ) should return 1 because it is there just once on the Stack. On the other hand, for a stack containing top- (1) (1) (2) (3) (5) (5) (2), count( 12 ) should return 0 because there are no values on the stack that equal 12.

This new operation should have the signature:

int Stack<Object>::count( const Object & data ) const;

Because it has been marked const, this method is saying that it is read-only. When your implementation runs, you won't be able to actually change any data members of the Stack passed to your method. Create a test driver program that exercises each of these exercises to satisfy yourself that your implementation is correct. For example, you should print the Stack before and after invoking the operation.

Explanation / Answer

bool Stack<Object>::allSmaller( const Object & data ) const
{
   int top=0,flag=0,s;
   n=data;
   s=stack.size();
   while(top<s)
   {
   //finding if stack element is smaller than given element
       if(stack[top]<n)
           flag++;
       top++;
   }
   if(flag == s)
       return true;
   return false;
      
}

int Stack<Object>::count( const Object & data ) const
{
   int top=0,flag=0,s;
   n=data;
   s=stack.size();
   while(top<s)
   {
   //finding if stack element equals given element
       if(stack[top]==n)
           flag++;
       top++;
   }
   return flag;
}