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

Unusual Behaviour of printf statement inside loop

I am new to programming world, I made a program to check if the given number is prime or not, but it is showing unusual behaviour.

My code:

#include <stdio.h>

void main()
{
    int n;

    printf("Enter n:");
    scanf("%d", &n);

    for (int i = 0; i <= n - 1; i++)
    {
        if (n % i == 0)
        {
            printf("n is not a prime number!");
            break;
        }
        if (i == n - 1)
        {
            printf("n is prime!");
        }
    }
}

Expected Output:

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

Enter n:5
n is prime!

Actual Output:

Enter n:5

Reference Screenshot
Using VS Code and MinGW.
Thanks in Advance

>Solution :

For starters according to the C Standard the function main without parameters shall be declared like

int main( void )

In this for loop

for (int i = 0; i <= n - 1; i++)
{
    if (n % i == 0)
    //..

there is division by zero when i is equal to 0.

Apart from this any number prime or not prime is divisible by 1. So in any case the approach with this for loop is incorrect.

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