[Solved] C Program to find prime number


I just modified your function a little. Here is the code

#include <stdio.h>
#include <math.h>

int prime(int a)
{
    int b=2,n=0;

    for(b=2; b<a; b++)
    {
        if (a%b==0)
        {
            n++;
            break;
        }
    }

    return(n);
}
int main(void)
{

    int c, answer;

    printf("Please enter the number you would like to find is prime or not= ");
    scanf("%d",&c);

    answer = prime(c);

    if(answer==1)
    {
        printf("%d is not a prime number \n",c);
    }
    else
    {
        printf("%d is a prime number\n",c);
    }

    return 0;
}

Explanation-

  1. In the for loop, I am starting from 2 because, I want to see if the given number is divisible by 2 or the number higher than 2. And I have used break, because once the number is divisible, I don’t want to check anymore. So, it will exit the loop.
  2. In your main function, you had not assigned properly for the printf() statement. If answer==1, it is not a prime number. (Because this implies that a number is divisible by some other number). You had written, it is a prime number(which was wrong).

If you have any doubts, let me hear them.

5

solved C Program to find prime number