edwina lai
edwina lai

Reputation: 37

C program: print prime number between 1 to 100

I was just wondering why my code doesn't work. Yes I know that it's easy to find answers online but I just wanted to delve in why the things I do doesn't function well rather than simply getting answers.

#include <stdio.h>

int main() {
    int i;
    int j;
    printf("all prime numbers between 1 and 100\n");
    for (i = 2; i <= 100; ++i) {
        if (i % !i != 0 && i>0 ) {
            printf("%d ", i);
        }
    }
}

Upvotes: 0

Views: 2579

Answers (1)

klutt
klutt

Reputation: 31366

As you have noticed yourself, there are tons of example code for this out there, so there's little point for me in showing how to calculate primes. So instead, I show how to debug your code. In this case I'd doe something like this:

for (i = 2; i <= 100; ++i) {
    printf("i: %d !i: %d\n", i, !i);
    printf("i \% !i != 0: ", i % !i != 0);
    if (i % !i != 0 && i>0 ) {
        printf("%d ", i);
    }
}

The exact printouts is something that you have to find out for yourself. But start with individual values, and then look at more complicated expressions. Also, use parenthesis whenever unsure. I don't know exactly how the expression in your if statement is parsed. I can think of several possibilities. Like:

((i % !i) != 0) && (i>0)
(i % (!i != 0)) && (i>0)
(i % !i) != (0 && i>0)

The point here is that your code does not work, and you have a very messy expression that is hard to understand exactly what it does. So use parenthesis.

Another thing you should do with that expression is to motivate each part with words. Can you explain why you have i>0? Because that's always true, to it's completely pointless. Instead of asking why it doesn't work. Try to explain to yourself why it should work. Get more and more detailed until you find something that you cannot explain. Then you probably have your bug there.

The definition of a prime is that it is an integer strictly greater than one, and is not divisible by any other integers than itself and and one. So now it's your job to explain how i % !i != 0 && i>0 should be able to check if i is an integer or not. And take explicit examples. For instance, if i is 5, describe the process when i % !i != 0 && i>0 checks if it is divisible by 2. Then explain how it checks for divisibility by 3.

The very simple question to your answer why it does not work is because the algorithm is wrong. :)

Upvotes: 1

Related Questions