A program that dynamicaly allocates memory and increases and decreases size of array using stack.Initially array is of size 10.

#include "stdafx.h"
#include <iostream>
using namespace std;
class stack
{
private:
      int *lifo;
           
      int top,size;
public:
      stack()
      {
            lifo=new int[10];
            size=10;
            top=0;

      }
      void push(int temp)
     
      {
           
     
            lifo[top++]=temp;
            if(top>size-1)
{           int *arr;
            cout<<"increasing the size of stack"<<endl;
            size=size+10;
            arr=lifo;
            lifo=new int[size];
            for(int i=0;i<top;i++)
            {
                  lifo[i]=arr[i];
            }
           
            delete[] arr;
      }
           
           
      }
      int pop()
      {    
            if(top%10==0)
      {     size=size-10;
            int *arr;
            arr=lifo;
            lifo=new int[size];
            for(int i=0;i<top;i++)
            {
                  lifo[i]=arr[i];
            }
            delete[] arr;
            }
            return lifo[top--];
      }
      int getsize()
      {
            return top;
      }
      int asize()
      {
            return size;
      }
      void display()
      {
            for(int i=top-1;i>=0;i--)
            {
            cout<<" element at "<<i<<"th index="<<lifo[i]<<endl;
            }
           
      }
};




int _tmain(int argc, _TCHAR* argv[])
{
      stack st;
      int x,ch,i;
     
      do
      {
            cout<<"1.Push Element"<<endl;
            cout<<"2.Pop Element"<<endl;
            cout<<"3.Display Elements"<<endl;
            cout<<"4.Exit"<<endl;
           
            cout<<"Enter your choice"<<endl;
            cin>>ch;
            switch(ch)
            {
                  case 1:
                        {
                       
                        cout<<"Enter number of elements to push"<<endl;
                        cin>>i;
                        for(int j=0;j<i;j++)
                        {
                        cout<<"enter element value";
                        cin>>x;
                        st.push(x);
                       
                        }
                        break;
                        }
                  case 2:
                        st.pop();
                        cout<<"\nOne element poped"<<endl;
                        break;
                  case 3:
                        st.display();
                        break;

            }
      }
      while(ch<4);
     
     
      return 0;
}

Comments

Popular posts from this blog

Using Progress Bar In C#

Get elements by class name in javascript

Jquery serer side datatables in asp.net