A C program and algorithm to implement stack in a single dimensional array – IGNOU MCA Assignment 2014 – 15

By | July 25, 2014

MASTER OF COMPUTER APPLICATIONS
Course Code : MCS-021
Course Title : Problem Solving and Programming
Assignment Number : MCA(1)/021/Assign/13
Assignment 2013

 

Implement stack in a single dimensional array. Write algorithms for various stack operations for them.

 

#include <stdio.h>
#define MAX 10 /* The maximum size of the stack */
void push(int [],int *,int);
void pop(int [],int *,int *);

void main()
{
int stack[MAX];
int top = -1;
int n,value;
do
{
do
{
printf(“Enter the element to be pushed\n”);
scanf(“%d”,&value);
push(stack,&top,value);
printf(“Enter 1 to continue\n”);
scanf(“%d”,&n);
} while(n == 1);

printf(“Enter 1 to pop an element\n”);
scanf(“%d”,&n);
while( n == 1)
{
pop(stack,&top,&value);
printf(“The value poped is %d\n”,value);
printf(“Enter 1 to pop an element\n”);
scanf(“%d”,&n);
}
printf(“Enter 1 to continue\n”);
scanf(“%d”,&n);
} while(n == 1);
getch();
}

void push(int stack[], int *top, int value)
{
if(*top < MAX )
{
*top = *top + 1;
stack[*top] = value;
}
else
{
printf(“The stack is full can not push a value\n”);
getch();
exit(0);
}
}

void pop(int stack[], int *top, int * value)
{
if(*top >= 0 )
{
*value = stack[*top];
*top = *top – 1;
}
else
{
printf(“The stack is empty can not pop a value\n”);
getch();
exit(0);
}
}

Program Code:

#include <stdio.h>
#define MAX 10 /* The maximum size of the stack */
void push(int [],int *,int);
void pop(int [],int *,int *);
void main()
{
int stack[MAX];
int top = -1;
int n,value;
do
{
do
{
printf("Enter the element to be pushed\n");
scanf("%d",&value);
push(stack,&top,value);
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);
printf("Enter 1 to pop an element\n");
scanf("%d",&n);
while( n == 1)
{
pop(stack,&top,&value);
printf("The value poped is %d\n",value);
printf("Enter 1 to pop an element\n");
scanf("%d",&n);
}
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);
getch();
}
void push(int stack[], int *top, int value)
{
if(*top < MAX )
{
*top = *top + 1;
stack[*top] = value;
}
else
{
printf("The stack is full can not push a value\n");
getch();
exit(0);
}
}
void pop(int stack[], int *top, int * value)
{
if(*top >= 0 )
{
*value = stack[*top];
*top = *top - 1;
}
else
{
printf("The stack is empty can not pop a value\n");
getch();
exit(0);
}
}

Screen Shots:

C_program_Stack_in_Array

 

C_program_Stack_in_Array_Out

Leave a Reply