C Program To Find Prime Numbers From 2 To N, using For Loop


Lets write a C program to find and print / display all the prime numbers from 2 to N. Here N is the user entered number / limit.

Prime Number: Any natural number which is greater than 1 and has only two factors i.e., 1 and the number itself is called a prime number.

Related Read:
Decision Control Instruction In C: IF
Nested For Loop In C Programming Language
break Statement In C Programming Language
C Program To Find Prime Number or Not using For Loop

Video Tutorial: C Program To Find Prime Numbers From 2 To N, using For Loop


[youtube https://www.youtube.com/watch?v=dz8lyJL_T6U]

YouTube Link: https://www.youtube.com/watch?v=dz8lyJL_T6U [Watch the Video In Full Screen.]

Outer For loop Logic

Outer for loop selects number one by one for each iteration. We initialize num to 2 and for each iteration num value increments by 1. Outer for loop executes until num is less than or equal to user entered limit times.

Inner For loop Logic

All the numbers are perfectly divisible by number 1, so we initialize the variable count to 2, instead of 1. So our inner for loop starts checking for divisibility from number 2.

The selected number(selected by outer for loop and stored in variable num), is divided by numbers 2 to num-1 times. If num is perfectly divisible by any number between 2 to num-1, then the number is not a prime number, else its a prime number.

Source Code: C Program To Find Prime Numbers From 2 To N, using For Loop

#include<stdio.h>
#include<math.h>

int main()
{
    int num, count, limit, prime, inum;

    printf("Enter the limit\n");
    scanf("%d", &limit);

    printf("Prime Numbers from 2 To %d are\n", limit);

    for(num = 2; num <= limit; num++)
    {
        prime = 1;
        inum  = sqrt(num);
        for(count = 2; count <= inum; count++)
        {
            if(num % count == 0)
            {
                prime = 0;
                break;
            }
        }

        if(prime)
            printf("%d\n", num);
    }

    return 0;
}

Output 1:
Enter the limit
25
Prime Numbers from 2 To 25 are
2
3
5
7
11
13
17
19
23

Output 2:
Enter the limit
41
Prime Numbers from 2 To 41 are
2
3
5
7
11
13
17
19
23
29
31
37
41

You can also watch C Program To Find Prime Numbers From 2 To N, using While Loop video tutorial.

Table of all prime numbers up to 1,000:

prime number or not

Note: We are not using curly braces around if statement because we only have 1 line of code after if – so curly braces are optional. If we have multiple lines of code, then we must use curly braces to wrap around the block of code.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

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