Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements