A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

C program to check a given number is prime or not using recursion
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)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now