user3348699
user3348699

Reputation: 41

Average of prime numbers in an array

Well, the problem is the above. To sum it up, it compiles, but I guess my main idea is just wrong. What I'm trying to do with that code is:

That's it. Any ideas? Keep in mind that I'm on the first period of engineering, so I'm not the best in programming.

The code is below:

#include <stdio.h>
#include <windows.h>
int main(void)
{
    int k, i, j, d, v[101], sum, prim, f;
    float ave;

    i = 0;

    while ((i < 101) && (j != 0) )
    {
        i++;
        printf("Set the value of the element %d => ", i);
        scanf("%d", &v[i]);
        printf("To stop press 0 => ");
        scanf("%d", &j);
    }
    k = 0;
    prim = 1;
    f = i;
    sum = 0;
    while (f > 2)
    {
        if (i % (f - 1) == 0)
        {
            prim = 0;
        }
        else
        {
            k++;
            sum = sum + v[f];
        }
        f = f - 1;
    }

    med = sum / k;
    printf("%d, %d, %d", k, soma, i);
    printf("The average is => %f \n", ave);
    system("pause");
}

For those wondering, this is what i got after the editing in the correct answer:

int main(void)
{
    int v[101];
    int n = 0;
    int k,j = 0;
    int i=0;
    int sum = 0;

    while( i<100 )
    {
        i++;
        printf ("Set the value of the element %d => ", i);
        scanf ("%d", &v[i]);
        int x,primo=1;
        if (i>1){
          for (x=2; x*x<=i; x++) {
            if (i % x == 0) primo = 0;
          }
          if(primo==1)
          {
             sum = sum+ v[i];
             n++;
          }
        }
        printf ("To stop press 0 => ");
        scanf ("%d", &j);
        if(j == 0)
            break;
    }

    float ave =(sum /n);
    printf("%d, %d, %d", n,i,sum);
    printf("The average is => %f \n", ave);
    system("pause"); 
}

Upvotes: 1

Views: 4322

Answers (4)

David C. Rankin
David C. Rankin

Reputation: 84551

Here is a cut at doing what you wanted. You don't need near the number of variables you originally had. Also, without knowing what you wanted to do with the prime number, I just output when a prime was encountered. Also as previously mentioned, using a function for checking prime really helps:

#include <stdio.h>
// #include <windows.h>

/* see: http://stackoverflow.com/questions/1538644/c-determine-if-a-number-is-prime */
int IsPrime(unsigned int number) {
    if (number <= 1) return 0; // zero and one are not prime
    unsigned int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

int main(void)
{
    int i, v[101], sum, pcnt=0, psum=0;
    float ave;

    i=0;

    printf ("\nEnter array values below, use [ctrl + d] to end input\n\n");
    printf ("Set the value of the element %d => ", i);
    while((i<101) && scanf ("%d", &v[i]) != EOF ){
        sum += v[i];
        if (IsPrime (v[i]))
            psum += v[i], pcnt++;
        i++;
        printf ("Set the value of the element %d => ", i);
    }

    ave=(float)psum/pcnt;

    printf("\n\n  Number of elements     : %d\n",i);
    printf("  The sum of the elements: %d\n",sum);
    printf("  The number of primes   : %d\n",pcnt);
    printf("  The average of primes  : %f\n\n", ave); 

    return 0;
}

Sample Output:

Enter array values below, use [ctrl + d] to end input

Set the value of the element 0 => 10
Set the value of the element 1 => 20
Set the value of the element 2 => 30
Set the value of the element 3 => 40
Set the value of the element 4 => 51
Set the value of the element 5 => 11
Set the value of the element 6 => 37
Set the value of the element 7 =>

Number of elements     : 7
The sum of the elements: 199
The number of primes   : 2
The average of primes  : 24.000000

Upvotes: 1

quantdev
quantdev

Reputation: 23793

First lets make a readable method to test if a number is prime; this answer from another SO post gives us a good one:

int IsPrime(int number) {
  int i;
  for (i=2; i*i<=number; i++) {
    if (number % i == 0) return 0;
  }
  return 1;
}

Second, let's clean your code, and compute a running sum of all the prime numbers encountered so far. Also, we will check the return values of scanf (but we should avoid scanf !)

And third, we add some indentation.

int main(void)
{

    int n = 0;
    int i = 0;
    int j = 0;
    int k = 0;
    int sum = 0;

    while( i<101 )
    {
       i++;
       printf ("Set the value of the element %d => ", i);
       if(scanf ("%d", &k) != 1)
           continue;

       if(is_prime(k))
       {
        sum += k;
        ++n;
       }

       printf ("To stop press 0 => ");
       if(scanf ("%d", &j) == 1)
          if(j == 0)
              break;
    }

    float ave = sum / (double) n;
    printf("The average is => %f \n", ave);
    system("pause");
}

Upvotes: 3

Parth Sane
Parth Sane

Reputation: 587

Here's the solution to your problem. Very easy stuff.

/* C program to find average of all prime numbers from the inputted array(you can predefine it if you like.) */        

#include <stdio.h>
#include <conio.h>
void main()
{
    int ar[100], i, n, j, counter;
    float avg = 0, numprime = 0;
    printf("Enter the size of the array ");
    scanf("%d", &n);
    printf("\n Now enter the elements of the array");
    for (i = 0; i < n; i++)
    {
        scanf("%d", &ar[i]);
    }
    printf(" Array is -");
    for (i = 0; i < n; i++)
    {
        printf("\t %d", ar[i]);
    }
    printf("\n All the prime numbers in the array are -");
    for (i = 0; i < n; i++)
    {
        counter = 0;
        for (j = 2; j < ar[i]; j++)
        {
            if (ar[i] % j == 0)
            {
                counter = 1;
                break;
            }
        }
        if (counter == 0)
        {
            printf("\t %d", ar[i]);
            numprime += 1;
            avg += at[i];
        }
    }
    avg /= numprime;
    printf("Average of prime numbers is ℅f", avg);
    getch();
}

You just need counter variables like above for all average computations. (Cause we need to know number of prime numbers in the array so we can divide the total of them and thus get average.) Don't worry about typecasting it is being done downwards... This solution works. I've written it myself.

Upvotes: 1

sir psycho sexy
sir psycho sexy

Reputation: 800

Well there are a few things to say. First the easy part: if the max number of integers allowed to read is 100 your variable "v" should be v[100]. This is not a char array, so this array don't need to have an extra element (v[100] will be an array of int that goes from v[0] to v[99]; adjust the loop limit too).

Also, you are checking if the number you have is prime in the variable f, but this var is assigned with the variable i and i is not an element of the array. You want to assign f something like v[i] (for i equal to 0 to the count of numbers read minus one). So you will need 2 loops: the one you are using now for checking if the number is prime, and another one that assigns v[i] to f.

Another thing to say is that you are calling scanf two times for reading, you could just read numbers and store it in a temporary variable. If this number is not zero then you store it in the array and keep reading, else you stop the reading.

By last I strongly recommend you set var names that make sense, use single letters only for the index variables; names like temp, array, max and countnumbers should appear in your code. It will be easier for you and everyone else to read your code, and you will reduce the number of mistakes.

Upvotes: 1

Related Questions