Check whether a given number is a prime or not | Prime number program in C, C++ and Java

Prime number program in C is discussed below in various methods. You can check if a given number is prime or not

  • using for loop
  • using functions
  • using pointers and
  • using recursion 

A number is said to be prime if it is divisible by 1 and itself. It should not have any other divisors.

prime number program

Prime number program using various methods

// C program to check if the given  number is prime or not

#include<stdio.h>

int main()
{
int n,i;
printf(“\nEnter the number : “);
scanf(“%d”,&n);

for(i = 2; i <= n/2; i++)
{
if(n % i ==0)
{
break;
}
}
if(i > n/2)
printf(“\n%d is a Prime Number\n”,n);
else
printf(“\n%d is not a Prime Number\n”, n);
return 0;
}

// Prime number program in c using pointers

#include<stdio.h>

int is_prime_number(int *p)
{
int i;
for(i = 2; i <= *p/2; i++)
{
if(*p % i ==0)
{
break;
}
}
if(i > *p/2)
printf(“\n%d is a Prime Number\n”,*p);
else
printf(“\n%d is not a Prime Number\n”, *p);
}
int main()
{
int n,i;
printf(“\nEnter the number : “);
scanf(“%d”,&n);
int *p = &n;
is_prime_number(p);
return 0;
}

// C  program to check if the given  number is prime or not

#include<stdio.h>

int is_prime_number(int n)
{
int i;
for(i = 2; i <= n/2; i++)
{
if(n % i ==0)
{
break;
}
}
if(i > n/2)
printf(“\n%d is a Prime Number\n”,n);
else
printf(“\n%d is not a Prime Number\n”, n);
}
int main()
{
int n,i;
printf(“\nEnter the number : “);
scanf(“%d”,&n);
is_prime_number(n);
return 0;
}

#include<stdio.h>
int is_prime_number(int num, int i)
{
if(num < 2)
{
printf(“\nEnter numbers greater than 1\n”);
exit(0);
}
if (i == 1)
{
return 1;
}
else
{
if (num % i == 0)
{
return 0;
}
else
{
return is_prime_number(num, i – 1);
}
}
}

int main()
{
int n, flag;
printf(“Enter a number: “);
scanf(“%d”, &n);

flag = is_prime_number(n, n / 2);
if (flag == 1)
{
printf(“\n%d is a prime number\n”, n);
}
else
{
printf(“\n%d is not a prime number\n”, n);
}
return 0;
}

The given number N, a positive integer, will be passed to the program using the first command line parameter. If it is a prime number the output should be the square root of the number up to 2 decimal point precision, If it is not a prime number then print 0.00 to stdout.

Solution:

#include<stdio.h>
#include int main(int a, char *b[])
{
int number,i,flag = 1;
number = atoi(b[1]);
for(i=2; i<number; i++)
{
if(number%i == 0)
{
flag = 0;
break;
}
}
if(flag == 1)
printf(“%.2f”,sqrt(number));
else
printf(“0.00”);
return 0;
}

Output:

prime number program in c