Home > database >  Unusual Behaviour of printf statement inside loop
Unusual Behaviour of printf statement inside loop

Time:12-24

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:

Enter n:5
n is prime!

Actual Output:

Enter n:5

Reference Screenshot
Using VS Code and MinGW. Thanks in Advance

CodePudding user response:

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.

  • Related