Home »
C programs »
C looping programs
C program to print all prime numbers from 1 to N.
Problem statement
This program will read the value of N and print all prime numbers from 1 to N.
Logic
The logic behind implement this program - Run loop from 1 to N and check each value in another loop, if the value is divisible by any number between 2 to num-1 (or less than equal to num/2) - Here num is the value to check it is prime of not.
Print all PRIME numbers from 1 to N using C program
/*C program to print all prime numbers from 1 to N.*/
#include <stdio.h>
int checkPrime(int num)
{
int i;
int flg = 0;
/*if number (num) is divisble by any number from 2 to num/2
number will not be prime.*/
for (i = 2; i < (num - 1); i++) {
if (num % i == 0) {
flg = 1;
break;
}
}
if (flg)
return 0;
else
return 1;
}
int main()
{
int i, n;
printf("Enter the value of N: ");
scanf("%d", &n);
printf("All prime numbers are from 1 to %d:\n", n);
for (i = 1; i <= n; i++) {
if (checkPrime(i))
printf("%d,", i);
}
return 0;
}
Output
Enter the value of N: 100
All prime numbers are from 1 to 100:
1,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,
C Looping Programs »