this code have to print all the prime numbers from 1 to 100 but when i run it cmd crash

#include <stdio.h>

int main(){

int a,b,c,d;
    for(a = 0;a <= 100;a++){
        d = 0;
        for(b = 0;b <= 100;b++){
            c = a % b;
            if (c == 0)
                d++;
            if (d > 2)
                break;
        }
        if (d == 2)
            printf("%d\n", a);
    }

    return 0;
}

Line 8 initialising b to 0 means that at line 9 you get a divide by zero error while trying to get the remainder after dividing a by b.

The problem is that, just as with division, taking the modulo of a number by zero is undefined; what you are actually getting is a division by zero exception, as internally, both division and modulo (or rather, strictly speaking, remainder) are calculated using the same assembly instruction. Thus, this is one place where you actually want to initialize b to one instead of zero. No, on second thought, start at 2 - there's no point in starting at 1, as every number is divisible by that, and it would give you a false negative for everything.

I might also suggest that you only iterate b from 1 to ciel(sqrt(a)), as you know that no prime divisor of a number is going to be more than that number's square root.

 for(b = 2; b <= (int) ciel(sqrt(a)); b++){

Finally, you might want to actually print the results when you find a prime number other than 2. Just sayin'.

Anyway, here is a simplified version of your code, though it assumes that the C99 <stdbool.h> library is available (it should be, with any compiler newer than, say, 2004). It isn't actually tested, but it should fix most of the problems in the original.

#include <stdio.h>
#include <stdbool.h>

int main() {

    int a, b, c;
    bool composite;

    printf("2, "); 

    for(a = 3; a <= 100; a += 2) {
        composite = false;

        for(b = 2; b <= (int) ciel(sqrt(a)); b++) {
            c = a % b;
            if (c == 0) {
                composite = true;
                break;
            }
        }
        if (!composite) {
            printf("%d, ", a);
        }
    }

    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.