Ab Be
Ab Be

Reputation: 67

For loop without any statement

This program tells whether a given input is prime or not but I don't understand what exactly the for loop does here? It has no brackets and no statements in it.

int main(void)
{
    int n;

    printf("Enter an integer number (> 1): ");
    if (scanf("%d", &n) != 1 || n <= 1) {
        printf("Invalid input. Quit!\n");
        return -1;
    }

    int d;
    for (d = 2; n % d != 0; d++)
        ;

    if (d == n)
        printf("%d is prime\n", n);
    else
        printf("%d divides into %d\n", d, n);

    return 0;
}

Upvotes: 1

Views: 3715

Answers (2)

Georg
Georg

Reputation: 94

The loop still checks the condition n % d != 0 and increases d at every cycle. As soon as n can be divided by d without reminder, d will not increase anymore and the loop exits. So you have your d.

Then you can find whether the number is prime with the condition following: If there was's a factor found lower than n, it's not prime. It's prime if there was no other factor.

Upvotes: 0

Barmar
Barmar

Reputation: 780871

It doesn't need a body, the purpose is just to increment d until the condition n % d != 0 is false (i.e. when n % d == 0 is true). It's not doing anything with d during this process.

At the end of the loop, d will be the lowest factor of n. If d == n it means that n doesn't have any factors other than itself and 1 (which isn't checked, since the loop starts at d = 2), i.e. it's prime.

Upvotes: 5

Related Questions