what is wrong with my code?

asked Sep 28, 2021
reshown Sep 28, 2021
#include<stdio.h>
#define max 6
int stack[max];
int top=-1;
void push(int data)
{
if(top==max-1)
{
printf("stack is full\n");
}
else{
top=top+1;
stack[top]=data;
}
}
int pop()
{
if(top==-1)
{
printf("stack is empty\n");
}
else{
int value=stack[top];
return value;
top=top-1;
}
}
void fact(int num) //PRIME FACTOR OF A NUMBER
{
int i=2;
while(num!=1)
{
while(num%i==0)
{
push(i);
num=num/i;
}
i++;
}
while(top!=-1)
{
printf("%d ",pop());
}
}
int main()
{
fact(120);
return 0;
}

+1 vote
answered Sep 28, 2021 by (5,130 points)
Like what you were trying to solve in this program and where you are not getting expected results.
answered Sep 28, 2021 by (88,520 points)
edited Sep 29, 2021 by Peter Minarik

After a function returns, no other calls are processed. For this, you have to do everything you want to do before calling return;

Your pop() function correctly:

```int pop()
{
if (top == -1)
{
printf("stack is empty\n");
}
else
{
int value = stack[top];
top = top - 1;
return value;
}
}```

Furthermore, your function fact(int num) doesn't work for all possible num values:

• if num is 0 the program ends up in an infinite loop.
• if num is 1 nothing is printed. (Maybe print 1 or "no prime divisor")
• if num is a negative number (the argument being int allows this) the program ends up in an infinite loop.
• if num has more than 6 divisors the program does not work correctly. Maybe increase the max to have something more forgiving, e.g. 31. (Why 31? Your input is int. Int is 32 bits with 1 bit reserved for the sign, so 231-1 is the highest number on int.)