Stack implementation in C++/C

·

1 min read

//Stack implementation in C++/C
#include <iostream>
using namespace std;
int top =-1;

void push(int * p,int size);
void pop();
void print(int *p,int size);
int peak(int *p);


int main() {

   int arr[3];
   int size=sizeof(arr)/sizeof(arr[0]);
   push(arr,size);
   push(arr,size);
   push(arr,size);
   push(arr,size);
   push(arr,size);
   print(arr,size);
   pop();
   cout<<endl;
   print(arr,size);
   cout<<endl;
   cout<<"The peak value is : "<< peak(arr);
   return 0;
}

void push(int * p,int size){
  top++;
  if(top<=size-1){
    int element;
    cout<<"Enter the element you want to insert or push in the array : ";
    cin>>element;
    p[top]=element;
    cout<<"top is: "<<top<<endl;

  }
  else{
    top--;
    cout<<"Stack overflow, can't insert any more element"<<endl;
  }


}
void pop(){
    --top;
    // cout<<"\npop function called , TOP : "<<top<<endl;
}
void print(int *p,int size){
     cout<<"[ ";
    for (int i=0;i<=top;i++){

        cout<<p[i]<<" ";
    }
    cout<<"]";

}

int peak(int *p){
    return p[top];
}