C Program To Find Prime Numbers From 1 To 300 using For Loop


Lets write a C program to print all the prime numbers from 1 to 300. (Hint: Use nested loops, break and continue).

Prime Number: is a natural number greater than 1, which has no positive divisors other than 1 and itself.

Note: Number 1 is neither prime nor composite number.

Related Read:
Nested For Loop In C Programming Language
C Program To Find Prime Number or Not using For Loop

Continue Statement In C Programming Language
break Statement In C Programming Language

Video Tutorial: C Program To Find Prime Numbers From 1 To 300 using For Loop


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

YouTube Link: https://www.youtube.com/watch?v=a9GtETARgPk [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 1 and for each iteration num value increments by 1. Outer for loop executes until num is less than or equal to 300.

Inner For loop Logic

All the numbers are perfectly divisible by number 1, so we initialize the variable i 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 1 To 300 using For Loop

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

int main()
{
    int num, count, i, prime;

    printf("Prime Numbers from 1 To 300 are\n");

    for(num = 1; num <= 300; num++)
    {
        if(num == 1)
        {
            printf("Number 1 is neither prime nor composite\n");
            continue;
        }

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

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

    return 0;
}

Output:
Prime Numbers from 1 To 300 are
Number 1 is neither prime nor composite
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
211
223
227
229
233
239
241
251
257
263
269
271
277
281
283
293

Table of all prime numbers up to 1,000:

prime number or not

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 *