2️⃣C Program to check Prime Number(With Program and Explanation)

 

C Program to Check Prime Number

๐Ÿ”น Introduction

A prime number is a natural number greater than 1 that has exactly two distinct positive divisors: 1 and itself. In this post, we will write a C program to check whether a given number is prime or not.

This program is useful for beginners to understand loops, conditions, and basic number logic in C.


๐Ÿ”น Problem Statement

Write a C program to check whether a given number is a prime number or not.


๐Ÿ”น Algorithm

  1. Start

  2. Read an integer n

  3. If n ≤ 1, it is not prime

  4. Check divisibility from 2 to n/2

  5. If divisible, number is not prime

  6. Otherwise, number is prime

  7. Stop


๐Ÿ”น Source Code (C Program)

#include <stdio.h> int main() { int n, i, flag = 0; printf("Enter a number: "); scanf("%d", &n); if (n <= 1) { flag = 1; } for (i = 2; i <= n / 2; i++) { if (n % i == 0) { flag = 1; break; } } if (flag == 0) printf("%d is a Prime Number.", n); else printf("%d is not a Prime Number.", n); return 0; }

๐Ÿ”น Output

Example 1:

Enter a number: 7 7 is a Prime Number.

Example 2:

Enter a number: 10 10 is not a Prime Number.

๐Ÿ”น Explanation

  • The program first checks if the number is less than or equal to 1

  • It then checks divisibility from 2 to n/2

  • If the number is divisible by any value in this range, it is not prime

  • Otherwise, it is a prime number


๐Ÿ”น Time Complexity (Beginners will learn this concept later on)

  • O(n) (can be optimized to √n)


๐Ÿ”น Optimized Version (Optional – Extra Value for Readers)

   # (Beginners will learn this concept later on)

#include <stdio.h> #include <math.h> int main() { int n, i, flag = 0; printf("Enter a number: "); scanf("%d", &n); if (n <= 1) { printf("%d is not a Prime Number.", n); return 0; } for (i = 2; i <= sqrt(n); i++) { if (n % i == 0) { flag = 1; break; } } if (flag == 0) printf("%d is a Prime Number.", n); else printf("%d is not a Prime Number.", n); return 0; }

๐Ÿ”น Conclusion

This C program efficiently checks whether a number is prime. Beginners should first understand the basic version and then move to the optimized approach using sqrt(n).


๐Ÿ“˜ C Programming Series – What’s Next?

๐Ÿ‘‰ In the next post of this series, we will learn how to write a C Program to Check Armstrong Number, with complete explanation and output examples. Stay tuned! ๐Ÿš€


Comments

Popular posts from this blog

⓮C Program to calculate Simple Interest (With Program and Explanation)

⑫ C Program to Swap Two Numbers Without Using a Temporary Variable (With Program and Explanation)

9️⃣C Program to Find LCM of Two Numbers (With Program and Explanation)