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)
            if (d > 2)
        if (d == 2)
            printf("%d\n", a);

    return 0;
4 Years
Discussion Span
Last Post by Schol-R-LEA

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;
        if (!composite) {
            printf("%d, ", a);

    return 0;

Edited by Schol-R-LEA

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.