C Program to find Prime Numbers

What are Prime numbers?

Numbers which are either divisible by 1 or itself are known as Prime Numbers. For example, 11 is a prime number because it is only divisible by 1 and 11. However, number 6 is not prime since it is divisible by 2 and 3.

The following is a C program to print the prime numbers between 2 and 50.

Expected Output:

How it works:

To check for a prime number we successively divide a number n from 2 to n-1. If n is not divisible by any number between this range then it is a prime number.

Example 1: Is 5 a prime number?

Question Statement Result
Is 5 is divisible by 2 5 % 2 == 0 0 (false)
Is 5 is divisible by 3 5 % 3 == 0 0 (false)
Is 5 is divisible by 4 5 % 4 == 0 0 (false)

Hence, 5 is a prime number.

Example 2: Is 6 a prime number

Question Statement Result
Is 6 is divisible by 2 6 % 2 == 0 1 (true)

Number 6 is divisible by 2. Hence, it is not a prime number.

Check Prime Numbers using a user-defined function

The following is a C program to check prime numbers using a user-defined function.

Expected Output:

1st run:

2nd run:


Recommended Reading:

Leave a Comment

%d bloggers like this: