Write a C program to find sum of all prime numbers between 1 to n using for loop. C program to generate sum of all primes between a given range.

Input: n=10

Output: Sum of all prime numbers between 1 to 10 = 2 + 3 + 5 + 7 = 17

Before calculating sum of all prime numbers between 1 to n we must first know how to list all prime numbers between 1 to n in C.

**Example:**Input: n=10

Output: Sum of all prime numbers between 1 to 10 = 2 + 3 + 5 + 7 = 17

### Required knowledge:

Basic C programming, If else, For loop, Nested loops#### Prime numbers:

Prime numbers are the positive integers greater than 1 that has only two divisors 1 and the number itself. Example: 2, 3, 5, 7, 11 are the first 5 prime numbers.Before calculating sum of all prime numbers between 1 to n we must first know how to list all prime numbers between 1 to n in C.

### Program:

/** * C program to find sum of all prime numbers between 1 to n */ #include <stdio.h> int main() { int i, j, n, isPrime, sum=0; /* * Reads a number from user */ printf("Find sum of all prime between 1 to : "); scanf("%d", &n); /* * Finds all prime numbers between 1 to n */ for(i=2; i<=n; i++) { /* * Checks if the current number i is Prime or not */ isPrime = 1; for(j=2; j<=i/2 ;j++) { if(i%j==0) { isPrime = 0; break; } } /* * If i is Prime then add to sum */ if(isPrime==1) { sum += i; } } printf("Sum of all prime numbers between 1 to %d = %d", n, sum); return 0; }

**Note:**For checking whether a number is Prime or not we just need to check that the number should not be divisible by any number between 2 to n-1. Apart from that you can also check between 2 to n/2. Since any number more than (n/2)+1 cannot be exactly divided by n except self n.

Output

Find sum of all prime between 1 to : 10

Sum of all prime numbers between 1 to 10 = 17

Sum of all prime numbers between 1 to 10 = 17

### You may also like

- Loop programming exercises index.
- C program to find sum of all natural numbers between 1 to n.
- C program to find the sum of all even numbers between 1 to n.
- C program to find the sum of all odd numbers between 1 to n.
- C program to find sum of all elements of an array.
- C program to calculate sum of digits.
- C program to whether a number is Prime number or not.
- C program to check whether a number is Strong number or not.
- C program to print Fibonacci series up to n terms.
- C program to find reverse of any number.
- C program to check whether a number is palindrome or not.
- C program to print Pascal triangle up to n rows.
- C program to print different star(*) pattern series.

< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).