Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How will the value of i be incremented here?

This is a approach for Weather a number is prime or not

QUESTION:

int main()
{
    int i, num, b;
    printf("ENTER A NUMBER : \n");
    scanf("%d", &num);

    for (i = 2; i <= num - 1; i++)
    {
        if (num % i == 0)
            break;
    }
    if (i == num)
        printf("PRIME");
    else
        printf("NOT A PRIME");

    return 0;
}

How will the value of i will be incremented if loop is completed..The condition for stopping is num-1 then how in next statement value of i will be == num

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Ex: if i enter 5 loop will run till 4 and value of i will be 4 then how will it will be == num..

Hope question is understood.

>Solution :

The body of the for loop is executed as long as the test condition is true. That means, when the loop stops executing because of the test condition (rather than because of the break), the test condition is false.

Therefore, when the loop ends this way, i <= num - 1 is false. Since num is 5, that means i <= 4 is false, which occurs when i has become 5.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading