This blog is under construction

Wednesday, 10 July 2013

C program to find the sum of first n prime numbers

Write a C program to find the sum of first n prime numbers.


  #include <stdio.h>

  int main() {
        int i, n, count = 0, value = 2, flag = 1, total = 0;

        /* get the input value n from the user */
        printf("Enter the value for n:");
        scanf("%d", &n);

        /* calculate the sum of first n prime nos */
        while (count < n) {
                for (i = 2; i <= value - 1; i++) {
                        if (value % i == 0) {
                                flag = 0;
                                break;
                        }
                }
                if (flag) {
                        total = total + value;
                        count++;
                }
                value++;
                flag = 1;
        }

        /* print the sum of first n prime numbers */
        printf("Sum of first %d prime numbers is %d\n", n, total);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:5
  Sum of first 5 prime numbers is 28



No comments:

Post a Comment