🔄📚Intermediate
Check Prime Number By Creating Function
Function to check prime
This program demonstrates how to create a reusable function to check if a number is prime. Functions make code modular and reusable.
Program Code
prime_function.c
C
1#include <stdio.h>2#include <stdbool.h>34// Function to check if a number is prime5bool isPrime(int num) {6 if (num <= 1) return false;7 if (num <= 3) return true;8 if (num % 2 == 0 || num % 3 == 0) return false;9 10 for (int i = 5; i * i <= num; i += 6) {11 if (num % i == 0 || num % (i + 2) == 0)12 return false;13 }14 return true;15}1617int main() {18 int num;19 20 printf("Enter a number: ");21 scanf("%d", &num);22 23 if (isPrime(num)) {24 printf("%d is Prime\n", num);25 } else {26 printf("%d is Not Prime\n", num);27 }28 29 return 0;30}Output
Enter a number: 97
97 is Prime
Optimization: This uses an optimized algorithm that checks divisibility only up to √n, skipping multiples of 2 and 3 for better performance.
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials