Sum of the first N Prime numbers


The program to print the sum of the first N prime numbers uses the method to find n prime numbers and then add them to find the sum. This sum is saved to an integer that outputs the sum .

The code takes a number checks it for prime, if it is prime then adds it to the sum variable. Till n prime number it does the same and then after that it prints the sum.

Example Code

 Live Demo

#include <stdio.h>
int isprime(int j) {
   int count=0;
   for(int i = 2 ; i <= j/2; i++) {
      if(j%i == 0) {
         count = 1;
      }
   }
   if(count == 0) {
      return 1;
   }
   else
      return 0;
}
int main(void) {
   int n = 5;
   int i=0, j= 1;
   int sum = 0;
   while(1) {
      j++;
      if(isprime(j)) {
         sum += j;
         i++;
      }
      if(i == n) {
         break;
      }
   }
   printf("The sum of first %d prime numbers is %d", n, sum);
   return 0;
}

Output

The sum of the first 5 prime numbers is 28
raja
Published on 15-Jul-2019 15:48:23
Advertisements