Q:

C program to check a given number is prime or not using recursion

0

C program to check a given number is prime or not using recursion

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Here, we will read an integer number from the user and then check the given number is a prime number or not using a recursive function.

Program:

The source code to check a given number is prime or not using recursion is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to check a given number is prime or not 
// using recursion

#include <stdio.h>

int checkPrime(int num, int i)
{
    if (i != 1) {
        if (num % i != 0) {
            return checkPrime(num, i - 1);
        }
        else {
            return 0;
        }
    }
    else {
        return 1;
    }
}

int main()
{
    int num = 0;

    printf("Enter a number: ");
    scanf("%d", &num);

    if (checkPrime(num, num / 2) == 1)
        printf("Given number is prime number");
    else
        printf("Given number is not prime number");

    return 0;
}

Output:

RUN 1:
Enter a number: 113
Given number is prime number

RUN 2:
Enter a number: 71
Given number is prime number

RUN 3:
Enter a number: 108
Given number is not prime number

RUN 4:
Enter a number: 21
Given number is not prime number

Explanation:

In the above program, we created two functions checkPrime() and main() function. The checkPrime() function is a recursive function, which is used to check a given number is a prime number or not.

In the main() function, we read an integer number from the user and then check the given number is a prime number or not using the checkPrime() function and printed the result on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C program to calculate the product of two numbers ... >>
<< C program to reverse an integer number using recur...