C Program to Find Sum of All Prime Numbers Between 1 to N

  • Write a C program to print all prime numbers between 1 to N using for loop.
  • Wap in C to print prime numbers between 1 to 100.

Required Knowledge

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....

Algorithm to check whether a number is prime number or not
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;    
    /* 
     * Take a number as input from user 
     */  
    printf("Enter a Number\n");  
    scanf("%d", &N);   

    /* Check for every number between 1 to N, 
       whether it is prime number or not  */
    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 between 1 to %d : %d", N,primeFactorSum);
    return 0;  
}

Output
Enter a Number
15
List of Prime Factors of 15
3 5
Enter a Number
50
List of Prime Factors of 50
2 5

Related Topics
C program to print all prime factors of a number
C program to find sum of prime numbers between 1 to N
C program to check whether a number is prime or not
C program to find sum of digits of a number using recursion
C program to reverse a number using recursion
C Program to calculate factorial of a number
C program to find perfect numbers between 1 to N using for loop
C program to find all roots of quadratic equation
C program to print all prime factors of a number
List of all C programs