w3resource logo


C Programming Exercises

C Exercises: Check a number is a prime number or not

Secondary Nav

C Recursion : Exercise-12 with Solution

Write a program in C to check a number is a prime number or not using recursion.
Test Data :
Input any positive number : 7
Expected Output :

The number 7 is a prime number.

C Code:

#include<stdio.h>

int checkForPrime(int,int);

int main()
{

    int n1,primeNo;

	printf("\n\n Recursion : Check a number is prime number or not :\n");
	printf("--------------------------------------------------------\n");
	
    printf(" Input any positive number : ");
    scanf("%d",&n1);

    primeNo = checkForPrime(n1,n1/2);//call the function checkForPrime

   if(primeNo==1)
        printf(" The number %d is a prime number. \n\n",n1);
   else
      printf(" The number %d is not a prime number. \nn",n1);
   return 0;
}

int checkForPrime(int n1,int i)
{
    if(i==1)
    {
        return 1;
    }
    else
    {
       if(n1 %i==0)
         return 0;
       else
         checkForPrime(n1,i-1);//calling the function checkForPrime itself recursively
    }
}

Flowchart :

Flowchart: Check a number is prime number or not.

C Practice online:

#include<stdio.h>

int checkForPrime(int,int);

int main()
{

    int n1,primeNo;

	printf("\n\n Recursion : Check a number is prime number or not :\n");
	printf("--------------------------------------------------------\n");
	
    printf(" Input any positive number : ");
    scanf("%d",&n1);

    primeNo = checkForPrime(n1,n1/2);//call the function checkForPrime

   if(primeNo==1)
        printf(" The number %d is a prime number. \n\n",n1);
   else
      printf(" The number %d is not a prime number. \nn",n1);
   return 0;
}

int checkForPrime(int n1,int i)
{
    if(i==1)
    {
        return 1;
    }
    else
    {
       if(n1 %i==0)
         return 0;
       else
         checkForPrime(n1,i-1);//calling the function checkForPrime itself recursively
    }
}

Improve this sample solution and post your code through Disqus.



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number