Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

main method not being executed

Tags:

c

Here is a program to find prime numbers using sieve of Eratosthenes. The program is compiling but on execution, it becomes non responsive.The print statement itself is not executed. Can I know where I have gone wrong?

#include<stdio.h>
int main()
{
    printf("Enter the range");
    int n,i;
    scanf("%d",&n);
    int j;
    int a[--n];
    for(i=0;i<n;i++)
            a[i]=i+2;
    for(i=0;i<n;i++)
            if(a[i])
            {
                    printf("%d",a[i]);
                    for(j=2;(i*j)<n;j++)
                            a[i*j]=0;
            }
    return 0;
}

Thanks

like image 822
Alok Mysore Avatar asked Mar 27 '26 13:03

Alok Mysore


2 Answers

Your program is infinite looping the first time through the loop.

When i = 0 this loop never ends:

for(j=2;(i*j)<n;j++)
like image 62
dcaswell Avatar answered Apr 02 '26 20:04

dcaswell


Your printf call might be being buffered which means it might not actually be printed until the buffer fills up or a newline is encountered.

Try adding a newline to the end of your string or call fprintf(stderr, ...) instead (which isn't buffered).

like image 27
tangrs Avatar answered Apr 02 '26 22:04

tangrs