The error that I'm struggling, with some examples
I have written a code for finding prime numbers using sieve of Eratosthenes algorithm, but the problem is my code works as it tends to be, but it shows an unspecified or undefined error for some numbers. It shows like "entering initial value (n) infinite times" as the error and for some numbers, I mentioned in the image, it works perfectly. As I started recently studying C in-depth I couldn't find what is going wrong. I request the code-ies to help me in this case, and also help me realize what is the mistake, why it happens and how to prevent it.
Edit: Actually it gets into error zone for smaller numbers, and as the number grows, it works fine and gets again into errors for some, like in the image specified.
Here's the code (modified to avoid garbage values):
#include <stdio.h>
int main()
{
int n;
printf("enter number: ");
scanf("%d",&n);
int arr[n],pr=2;
for(int i=0;pr<=n;i++)
{
arr[i]=pr;
pr++;
}
int j,k=0;
while(arr[k]<=n)
{
for(j=2;j<n;j++)
{
for(k=0;k<n;k++)
{
if(arr[k]%j==0 && arr[k]>j)
arr[k]=0;
}
}
}
for(int i=0;i<n;i++)
{
if(arr[i]>0)
printf(" %d",arr[i]);
}
printf("\n");
return 0;
}
nis not too big, to overflow the stack; 2) You loop initializingarr, are you sure it will initialize all elements ofarr? And that it will not go out of bounds ofarr?while(arr[k]<=n)you usekuninitialized. Which means it will have an indeterminate value (which may not be zero). You also usekfor more than one thing. And if the initial indeterminate value ofkis non-negative, it will go out of bounds.for(i=0;pr<=n;i++) { arr[i]=pr;is one-too-many: usefor(i=0;pr<n; i++)