Answer to Question #333179 in C for lota

Question #333179

Create a function which receives a pointer of array as a parameter and calculates the sum of prime

numbers and sum of non_prime numbers in that array. Then compares them to find out which one is

larger (sum of prime or sum of non_prime). Return both sum of prime and sum of non_prime numbers

also and print those in the main function.


1
Expert's answer
2022-04-24T17:15:58-0400


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <malloc.h>
//define a function wich check the number for prime 
int isPrime(int num)
{
  for(int i=2;i*i<=num;i++)
    if(num%2==0)
      return 0;
  return 1;
}
//define base function
void sumPrimeAlso(int *ar,int size,int *sumPrime,int *sumNonPrime,int *comp)
{
  for(int i=0;i<size;i++)
    {
      if(isPrime(ar[i]))
        *sumPrime=*sumPrime+ar[i];
      else
        *sumNonPrime=*sumNonPrime+ar[i];
    }
  *comp=*sumPrime-*sumNonPrime;
}
int main(void) {
   int n;
  printf("Size of array:");
  scanf("%i",&n);
  int *ar=(int*)malloc(sizeof(int)*n);
  for(int i=0;i<n;i++)
    {
      scanf("%i",&ar[i]);
    }
  int sumP=0;
  int sumNonPrime=0;
  int cmp;
  sumPrimeAlso(ar,n,&sumP,&sumNonPrime,&cmp);
  printf("Summ of prime numbers: %i\n",sumP);
  printf("Summ of non prime numbers: %i\n",sumNonPrime);
  if(cmp)
    printf("sum of prime number higher than sum of non prime");
  else
    printf("sum of prime number less than sum of non prime");
  free(ar);
  return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS