A prime number is a positive integer which is divisible only by 1 and itself. For example: 2, 3, 5, 7, 11, 13
#include <stdio.h>
int checkPrime(int number);
int main()
{
int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);
if(n <= 0)
{
printf("Enter positive number only.");
exit(0);
}
//Function call...
flag = checkPrime(n);
if (flag==1)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}
//Function to check prime number int checkPrime(int number)
{
int i, flag=1;
for(i=2; i<=number/2; ++i)
{
//checks nonprime number
if(number%i==0)
{
flag=0;
break;
}
}
return(flag);
}
Output of program
Run-1
Enter a positive integer: 13
13 is a prime number.
Run-2
Enter a positive integer: 10
10 is not a prime number.
Run-3
Enter a positive integer: -5
Enter positive number only.
Nice blog
ReplyDelete