In this C program, we will learn to print all prime numbers between 1 to N using for loop. A Prime number is a natural number greater than 1 that is only divisible by either 1 or itself. Here is the list of first few prime numbers
2 3 5 7 11 13 17 19 23....
Required Knowledge
Algorithm to check whether a number is prime number or not
Let, N be a positive number.
Let, N be a positive number.
- For every number i, between 2 to N/2(2<= i <= N/2) check whether i divides N completely(check If i is a factor of N).
- if (N % i == 0), then N cannot be a Prime number.
- If none of the number between 2 to N/2 divides N completely then N is a prime number.
C program to print sum of all prime numbers between 1 to N
#include <stdio.h> int main() { int counter, N, i, isPrime, primeFactorSum = 0; printf("Enter a Number\n"); scanf("%d", &N); for(counter = 2; counter <= N; counter++) { isPrime = 1; for(i = 2; i <=(counter/2); ++i) { if(counter%i==0) { isPrime = 0; break; } } if(isPrime==1) primeFactorSum += counter; } printf("Sum of Prime Numbers : %d", N,primeFactorSum); return 0; }Output
Enter a Number 15 Sum of Prime Numbers : 41
Enter a Number 50 Sum of Prime Numbers : 328
Related Topics