Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

what is wrong with my code?

+6 votes
asked Sep 28, 2021 by Mohit Gusain (180 points)
reshown Sep 28, 2021 by Admin
#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;
}

2 Answers

+1 vote
answered Sep 28, 2021 by Admin (5,130 points)
Please consider adding more details in your question.
Like what you were trying to solve in this program and where you are not getting expected results.
0 votes
answered Sep 28, 2021 by Peter Minarik (88,130 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.)
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...