Prime Number Check in C Language: A Beginner's Guide

Beginners code hub
By -
0
Prime Number Check in C Language: A Beginner's Guide


What is a Prime Number?

A prime number is a natural number greater than 1 that has no divisors other than 1 and itself. For example, 2, 3, 5, 7, 11, and 13 are prime numbers.

Steps to Check for Prime Numbers in C

To determine if a number is prime, we:

1. Exclude numbers less than or equal to 1 (not prime).

2. Check if the number has any divisors other than 1 and itself.

3. If no divisors are found, the number is prime.

C Program to Check Prime Numbers

Here’s a simple program to check if a given number is a prime number:


    
      #include <stdio.h>

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

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

          if (num <= 1) {
              printf("%d is not a prime number.\n", num);
              return 0;
          }

          for (i = 2; i * i <= num; 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

1. Input the Number:

The program prompts the user to enter a number and stores it in the variable num.

2. Check for Prime Conditions:

If the number is less than or equal to 1, it is marked as not prime.

For numbers greater than 1, the program checks divisors from 2 to num / 2.

3. Prime Check Using Loop:

A for loop iterates through potential divisors.

If any divisor divides the number evenly, the number is not prime.



4. Output the Result:

Based on the isPrime flag, the program prints whether the number is prime or not.

Sample output 

Input 1
Prime Number Check in C Language: A Beginner's Guide
Input 2
Prime Number Check in C Language: A Beginner's Guide




Tags:

Post a Comment

0Comments

Post a Comment (0)