C Program to Print Prime Numbers from 1 to N using For loop
ADVERTISEMENTS
C program to print prime numbers from 1 to N using for loop of any range. In this article, you will learn how to make a c program to print prime numbers from 1 to N using for loop.
Sample of Prime Numbers
2 3 5 7 .......... 83 89 97
Source Code
// C Program to Print Prime Numbers from 1 to N using For loop
#include <stdio.h>
int main() {
int x, i, j, f;
printf ("Enter the range number to print the prime numbers:\n");
scanf ("%d", &x);
printf ("\n\nThe prime numbers between 1 and %d are:\n\n", x);
for (i = 1; i <= x; i++) {
// They are niether prime nor composite if as skip 0 and 1
if (i == 1 || i == 0) {
continue;
}
f = 1;
for (j = 2; j <= i / 2; ++j) {
if (i % j == 0) {
f = 0;
break;
}
}
// f = 1 means i is prime and f = 0 means i is not prime
if (f == 1) {
printf ("%d ", i);
}
}
return 0;
}
Output
Enter the range number to print the prime numbers:
100
The prime numbers between 1 and 100 are:
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