Prime number in C using function

Spread the love

Program Description:

Write a program to check the given number is a Prime number in C using function, We will create a function called isPrime(), The function accepts a number as input and returns true if the number is a prime number. Otherwise, The function should return false.

Excepted Input and Output:


Enter a positive numbers: 89


Number 89 is a Prime Number


It is recommended to go through the C functions and Loops to understand the following program.

Prime number in C using function Algorithm:

  1. Accept a number from the user and store it in a variable named num
  2. Check if the num is a Negative number if (num <= 0) display an error message if num is a negative number.
  3. Create a function called isPrime. The isPrime function is used to check the prime number.
    • Prototype of isPrimebool isPrime(int);
    • The isPrime accepts an integer number as input ( n)
    • Returns true – if the n is prime number
    • Returns false – if the n is not a prime number.
    • This function returns a Boolean, So we need to include the stdbool.h header file. (We can also return int)
  4. Call the isPrime function from the main function and pass the input number num.
  5. The isPrime function will check to see if the given integer n is evenly divisible by any number by going through all numbers from 2 to num/2 ( n/2). The number n is not a prime number if it can be divided evenly by any of the aforementioned numbers. Otherwise, the number n is a prime number.
  6. Display the results on console based on the isPrime function return value.

Prime number in C using function Program:

Let’s write the program

Prototype Details of the isPrime function

  • bool isPrime(int n);
  • Function_name: isPrime
  • Arguments_list : (int n)
  • Return_value : bool

📢 As the isPrime function is called before defining, So we need to declare the function using function declaration or forward declaration.

bool isPrime(int n);

Program Output:

Compile and Run the program.

$ gcc isPrime.c

Test Case 1: Check Prime Numbers – Positive Numbers

Test Case 2: Negative Numbers


Programs Related to Prime number in c using a function:


Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

Leave a Reply