mercredi 16 septembre 2020

Can not run this C program - File Scope Error

I am trying to find the prime number using (Sieve of Eratosthenes) method but when I ran my program, I got this following error in CLion. The error is saying about the ara[size] in line 6. How can I fix that and run my program? I do not see any other error in my code. Also is there way I can make my code more efficient than this approach?

**error: variably modified 'ara' at file scope
    6 | int ara[size];
      |     ^~~
make[3]: *** [CMakeFiles/C_Practise.dir/build.make:83: CMakeFiles/C_Practise.dir/main.c.o] Error 1
make[2]: *** [CMakeFiles/Makefile2:96: CMakeFiles/C_Practise.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:103: CMakeFiles/C_Practise.dir/rule] Error 2
make: *** [Makefile:138: C_Practise] Error 2"**


    #include <stdio.h>
    #include <math.h>
    
    const int size = 40;
    int ara[size];
    
    void print_ara()
    {
        int i;
    
        for(i = 2; i < size; i++){
            printf("%4d", ara[i]);
        }
        printf("\n");
        for(i = 2; i < size; i++){
            printf("----");
        }
        printf("\n");
        for(i = 2; i < size; i++){
            printf("%4d", i);
        }
        printf("\n\n\n");
    }
    
    void sieve()
    {
        int i, j , root;
    
        for(i = 2; i < size; i++){
            ara[i] = 1;
        }
    
        root = sqrt(size);
        print_ara();
        for(i = 2; i <= root; i++){
            if(ara[i] == 1){
                for(j = 2; i * j <= size; j++)
                {
                    ara[i * j] = 0;
                }
                print_ara();
            }
        }
    }
    
    int is_prime(int n)
    {
        int i;
    
        if(n < 2) {
            return 0;
        }
    
        return ara[n];
    }
    
    int main()
    {
        int n, m;
    
        sieve();
    
        while (1){
            printf("Please enter a number(enter 0 to exit): ");
            scanf("%d", &n);
    
            if(n == 0) {
                break;
            }
            if(n >= size) {
                printf("The number should be less than %d\n", size);
                continue;
            }
    
            if(1 == is_prime(n)) {
                printf("%d is a prime number.\n", n);
            } else{
                printf("%d is not a prime number.\n", n);
            }
        }
        return 0;
    }

Aucun commentaire:

Enregistrer un commentaire