Saturday, November 14, 2020

Stack program - push,pop,peep,display,change,length,middle_element....... in c language.

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

#define MAX 10

int stack[MAX],top = -1;

void push();

int pop();

int peek();

void display();

void change();

int length();

int middle_ele();


void main()

{

    int ch;

    while(1)

    {

    printf("\n1.push \n2.pop \n3.peek \n4.display \n5.change \n6.length \n7.middle_element \n8.exit\n");

    printf("\nenter the choice : ");

    scanf("%d",&ch);

    switch(ch)

    {

        case 1: push(); break;

        case 2: pop(); break;

        case 3: peek(); break;

        case 4: display(); break;

        case 5: change(); break;

        case 6: length(); break;

        case 7: middle_ele(); break;

        case 8: exit(0);

        default : printf("\n invalid choice\n\n");

    }

  }

}

void push()

{

    int data;

    printf("enter the data : ");

    scanf("%d",&data);

    if(top==MAX-1)

    {

        printf("\n stack is full");

    }

    else

    {

        top++;

        stack[top]=data;

        printf("%d is inserted.\n",data);

    }

}

int pop()

{

    if(top==-1)

    {

        printf("stack is empty\n");

    }

    else

    {

        printf("%d is deleted.\n ",stack[top]);

        top--;


    }

}

int peek()

{

    if(top==-1)

     {

       printf("stack in empty.\n");

     }

    else

    {

       printf("%d is peek element.",stack[top]);

    }

}

void display()

{

    int i;

    if(top==-1)

      {

        printf("stack is empty");

      }

    else

    {

        printf("stack elements are :\t");

        for(i=0;i<=top;i++)

        {

            printf("%d\t",stack[i]);

        }

    }

}

void change()

{

   int p,ele;

   printf("enter the position where you wants to change the element :");

   scanf("%d",&p);

   if(top-p<-1)

   {

        printf("stack is underflow.\n");

   }

   else

   {

       printf("enter the new element : ");

       scanf("%d",&ele);

       stack[p-1]=ele;

       printf("~new element %d is inserted: ",stack[p-1]);

   }


}

int length()

{

    int count=0,i;

    for(i=0;i<=top;i++)

    {

        count=count+1;

    }

    printf("Length of the stack is : %d\n",count);

    return count;

}

int middle_ele()

{

    int n,ele,ele1,ele2;

    if(length()%2==0)

    {

        n=length()/2;

        ele1 = stack[n-1];

        ele2 = stack[n];

        printf("Middle element's of the stack are : %d  %d\n ",ele1,ele2);

    }

    else

    {

        n=length()/2;

        ele = stack[n];

        printf("Middle element of the stack is : %d\n",ele);

    }

}

OUTPUT :



No comments:

Post a Comment

Stack program - push,pop,peep,display,change,length,middle_element....... in c language.

#include<stdio.h> #include<stdlib.h> #include<conio.h> #define MAX 10 int stack[MAX],top = -1; void push(); int pop(); int...