In: Computer Science
Write a C function, for example void sumOfPrime(int n), that takes a positive int n as a parameter, put all prime numbers less than n into an array, and print out the array and the sum of the numbers in that array. You can use the isPrime function above to save time.
#include <stdio.h> int isPrime(int num){ int i; if (num <= 1) return 0; if (num % 2 == 0 && num > 2) return 0; for (i = 3; i < num / 2; i += 2){ if (num % i == 0) return 0; } return 1; } void sumOfPrime(int n){ int arr[1000]; int k = 0, sum = 0, i; for(i = 2;i<n;i++){ if(isPrime(i)){ arr[k++] = i; } } for(i = 0;i<k;i++){ printf("%d ",arr[i]); sum += arr[i]; } printf("\nSum = %d\n",sum); } int main() { int n; printf("Enter value for n: "); scanf("%d",&n); sumOfPrime(n); return 0; }
void sumOfPrime(int n){ int arr[1000]; int k = 0, sum = 0, i; for(i = 2;i<n;i++){ if(isPrime(i)){ arr[k++] = i; } } for(i = 0;i<k;i++){ printf("%d ",arr[i]); sum += arr[i]; } printf("\nSum = %d\n",sum); }