Search code examples
cprimes

Problems with printing output C


So I have to write a code for school. I did, but my outputs are not the way they asked for. This code gives me prime number between 2 different numbers. So i have to print those numbers in rows. But yeah there are getting zeros between the answers below you can see what I mean. How can I fix this?

#include <stdio.h>

int is_prime (int number)
{
    int is_prime= 1, i;

    if (number < 2)
    {
        is_prime = 0;
    }
    else
    {
        for(i = 2; (i * i) <= number; i++)
        {
            if ((number % i) == 0)
            {
                is_prime = 0;
                break;
            }
            else
            {
                is_prime = 1;
            }
        }
    }
    return is_prime;
}

int main (void)
{
    int lower_limit, upper_limit, i;

    scanf("%d\n%d", &lower_limit, &upper_limit);

    for(i = lower_limit; i <= upper_limit; i++)
    {
        if (is_prime (i))
        {
            printf("\n%d", i);
        }
        else
        {
            printf("\n%d", is_prime(i));
        }
    }

    return 0;
}

Output

0
11
0
13
0
0
0
17
0
19
0

Reference

11
13
17
19


Solution

  • It's in this if block:

        if (is_prime (i))
        {
            printf("\n%d", i);
        }
        else
        {
            printf("\n%d", is_prime(i));
        }
    

    What this says is "if the number is prime print it, otherwise print whether it is prime (which at this point you've established it's not)".

    Just get rid of the else block.