C Program to Check Whether the Given Number is Prime or Not

Introduction

Checking whether a number is prime is one of the most fundamental tasks in mathematics and programming. A prime number is greater than 1 and divisible only by 1 and itself. In this article, we’ll show you how to create a C program to check whether the given number is prime or not using basic loops and condition checks.


What is a Prime Number?

A prime number has exactly two distinct factors: 1 and itself. Examples of prime numbers include 2, 3, 5, 7, and 11. Numbers like 4, 6, 8, and 9 are not prime since they have more than two factors.


C Program to Check Prime Number

#include <stdio.h>

int main() {
int num, i, isPrime = 1;

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

if (num <= 1) {
isPrime = 0;
} else {
for (i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = 0;
break;
}
}
}

if (isPrime)
printf("%d is a Prime Number.\n", num);
else
printf("%d is Not a Prime Number.\n", num);

return 0;
}

Explanation of the Code

  • Input: Accept a number from the user.
  • Check:
    • If the number is less than or equal to 1, it’s not prime.
    • Loop from 2 to half of the number.
    • If the number is divisible by any of these, it is not prime.
  • Output: Display the result based on the check.

Sample Output

Enter a number: 17  
17 is a Prime Number.

Enter a number: 20
20 is Not a Prime Number.

Use Cases of Prime Number Logic in Programming

  • Cryptography
  • Data compression
  • Algorithmic challenges
  • Prime factorization applications

Conclusion

This C program to check prime number is a great example to practice loop and condition-based logic. You can further optimize it by checking up to the square root of the number instead of half, which improves performance in larger inputs.

Previous Article

C Program to Check Whether a Number is Prime or Not

Next Article

C Program to Evaluate the Series 1² + 2² + 3² + … + n²

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨