Write a C program to find the sum of first n prime numbers.
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
Enter the value for n:5
Sum of first 5 prime numbers is 28
Can you also please explain the logic ?????
ReplyDeleteSir can you perform same program using iostream library and loop concept please??
ReplyDeleteWhy you have taken at first value equals to 2?
ReplyDelete