Prime numbers are not listed

Asked

Viewed 61 times

-1

I’m trying to create a C program that shows all prime numbers from 1 to 100 using brute force, but my program shows nothing on the screen.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x=100,n=2,z=0;
    int p[z];
    verif:
    while(x!=1)
    {
        while(x%n!=0)
        {
            if(n==(x-1))
            {
                z++;
                p[z-1]=x;
                break;
            }
            n++;
        }
        x--;
        n=2;
        goto verif;
    }
    while(z>=0)
    {
        printf("%d",p[z]);
        z--;
    }
}
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

2

The biggest problem is that your array has zero elements, I think you wanted to work with 100 of them.

Let’s simplify the code?

#include <stdio.h>

int main() {
    int p[100];
    int z = 0;
    for (int x = 100; x > 1; x--) {
        for (int n = 2; x % n != 0; n++) {
            if (n == x - 1) {
                p[z++] = x;
                break;
            }
        }
    }
    while (z >= 0) printf("%d ", p[z--]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • It became much easier to understand, really simplified the code. Interestingly, you made a repository for the answers of Stack, I think I’ll start doing that too, I have some loose files here that I used to formulate response, I believe will facilitate the organization. : D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.