Re: stack



On 24 Dec 2006 02:50:36 -0800, "rhle.freak" <rhle.freak@xxxxxxxxx>
wrote:

This is a very simple implementation of push and pop functions of a
stack.ive compiled it on msvc++ on windows platform and it wrks fine.
ive used 'int' as the data for the push operations,however if i enter a
floating point number during runtime,it does not break out of the the
infinite loop.
what should i do in order to prevent this ??


#include<stdio.h>
#include<stdlib.h>
#define MAX 4

struct stack{
int top;
int item[MAX];
};

void push(struct stack *p,int n)
{
if(p->top==MAX-1)
printf("overflow\n");
else
p->item[++p->top]=n;
return;
}

void pop(struct stack *p)
{
if(p->top==-1)
printf("underflow\n");
else
{
printf("deleted number is %d\n",p->item[p->top]);
--p->top;
}
return;
}

void display(struct stack *p)
{
int i;
if(p->top==-1)
printf("stack is empty\n");
else
{
for(i=p->top;i>=0;i--)
printf("%d\n",p->item[i]);
}
return;
}

int main(void)
{
int num=0,choice;
struct stack s;
/* added variables*/
int done = 0;
int num_scanned;
s.top=-1;
for(;;)
while ( !done )
{
printf("Menu");
printf("\n1.Push");
printf("\n2.Pop");
printf("\n3.Display");
printf("\n4.Exit");
printf("\n5.Clear screen\n");
printf("Enter your choice :");
scanf_s("%d",&choice);
/* As others have pointed out, scanf_s() is not a standard C function
(it's a Microsoft extension "with security enhancements"), and always
check the return value of scanf().*/
num_scanned = scanf("%d",&choice);
if ( num_scanned == 1 )

switch(choice)
{
case 1:
printf("enter the number to push");
scanf_s("%d",&num);
push(&s,(int)num);
break;
case 2:
pop(&s);
break;
case 3:
display(&s);
break;
case 4:
exit(0);
/*Change that to:*/
done = 1;
break;
case 5:
system("cls");
Oops. Warning 616: control flows into case/default
default:
printf("wrong choice\n");
}
}
return 0;
/* If you keep exit(0), then:*/
Warning 527: Unreachable code at token 'return'
}

--
jay
.



Relevant Pages