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



3 comments:

  1. Can you also please explain the logic ?????

    ReplyDelete
  2. Sir can you perform same program using iostream library and loop concept please??

    ReplyDelete
  3. Why you have taken at first value equals to 2?

    ReplyDelete