Home > OS >  Using for loop statement in determining the 5 input numbers are prime and then display only the prim
Using for loop statement in determining the 5 input numbers are prime and then display only the prim

Time:12-17

I need to create a program that inputs five numbers from the user and needs to determine if it is prime and display the only prime number. I can't figure out how to display the prime numbers only.

#include<stdio.h>

int main()
{
    int n, c;
    
    printf("Enter a number: ");
    scanf("%d", & n);
    
    for (c = 2; c <= n / 2; c  )
    {
        if (n % c == 0)
        {
            printf("");
            break;
        }
    }
    if (c == n / 2   1)
        printf("%d is prime.\n", n);

    return 0;
}

CodePudding user response:

Code :

int main()
{
    int i, user_input, z, flag = 1;

    for (i = 0; i < 5; i  )
    {
        printf("Please enter a number:\n");
        scanf("%d", &user_input);


        // extreme cases:
        if (user_input == 1) // If user_input == 1 -> not a prime
        {
            
            continue;
        }
        if (user_input == 2) // If user_input == 2 -> it's a prime
        {
            printf("%d\n", user_input);
            continue;
        }

        // Normal cases: 
        for (z = 2; z * z <= user_input; z  )
        {
            // Is it NOT prime :
            if (user_input % z == 0)
            {
                flag = 0; break;

            }
        }
        if (flag)
        {
            printf("%d\n", user_input);
        }
        flag = 1;

    }
    return 0;
}
  •  Tags:  
  • c
  • Related