stack using dynamic memory allocation

 /*
Author : PATEL DIVYAKUMAR BHARATBHAI
Problem : Stack...using dynamic memory allocation...
Date : 24/09/2022
*/
#include <stdio.h>
#include <stdlib.h>
// Global variable declaration ...which helps to not pass values through functions to avoid mistakes... //
int *stack;
int top = -1, n;
// Function declaration //
void push();
void pop();
void display();
void main()
{
printf("Enter the number you want to make stack: ");
scanf("%d", &n);
stack = (int *)malloc(n * sizeof(n));
printf("1. PUSH \n2. POP \n3. DISPlAY \n");
while (1)
{
int ch;
printf("Enter your choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
default:
free(stack);
stack = NULL;
printf("BYE... ");
exit(0); // stdlib is needed to execute exit function... //
}
}
}
// Functions to execute stack code //
// PUSH function to push value in stack and change top reference... //
void push()
{
if (top == n - 1)
{
printf("stack is FULL \n");
}
else
{
int num;
printf("Enter the number you want to add: ");
scanf("%d", &num);
top++;
stack[top] = num;
}
}
// POP function to DELETE the last entered value... //
void pop()
{
if (top == -1)
{
printf("Stack is EMPTY \n");
}
else
{
printf("Deleted value is %d \n", stack[top]);
top--;
}
}
// DISPLAY function to display stack values... //
void display()
{
for (int i = 0; i <= top; i++)
{
printf("%d \n", stack[i]);
}
}

Post a Comment

0 Comments