1

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:

  • I want the person to give us the elements of the array, how many he wants to (with a limit of a 100 elements).
  • After that, I'm checking what array positions are prime numbers.(ex: position 2,3,5,etc. Not the elements itself).
  • After that, I'm doing the average of the values in the prime numbers position.

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"); 
}
user3348699
  • 41
  • 1
  • 5
  • Oh dear. Fix your indenting first, your code is really hard to read like that. And you would do well to introduce a function or two, say one called `isprime()` would help a lot. – Greg Hewgill Jun 09 '14 at 04:11
  • 2
    Also fix your variable names. A half-dozen or more single letter variables will mess up your thinking. Also, do you have to use while instead of for loops? And, break into more functions. One monolithic function with a mess of variables is asking for trouble... I know that's probably a lot to swallow but if you're gonna get good at this, the above is bread and butter! Simple function example: Create a function called `isPrime`. It will accept a single integer and return a true/false, (1/0) after analyzing the number for "primeness". – Paul Sasik Jun 09 '14 at 04:14
  • Never heard of that function, kinda hard to use that at moment. Also, sorry for the indenting, i'm not that organizate when it comes to technology =( – user3348699 Jun 09 '14 at 04:14
  • I meant `isprime()` is something that *you* write to help sort out your program logic. – Greg Hewgill Jun 09 '14 at 04:15
  • As for loops, i can use either while or for, but well, i can't see where i could use a for there.. – user3348699 Jun 09 '14 at 04:16
  • @GregHewgill: You whipped out the isPrime function suggestion 4 seconds faster! :-) – Paul Sasik Jun 09 '14 at 04:17

4 Answers4

3

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");
}
Community
  • 1
  • 1
quantdev
  • 23,517
  • 5
  • 55
  • 88
  • I would argue that the prime number tester is effective (it gives the correct answer), but grotesquely inefficient (it tests many more values than need to be tested). If the number is `97`, it will do 94 tests before concluding that it is prime. If written less inefficiently, it would take 9 tests, which is an order of magnitude less. The discrepancy is worse as the numbers get bigger. – Jonathan Leffler Jun 09 '14 at 05:03
  • @Jonathan: true, I edited with faster solution (from the same SO post), but looking for a better one. You will note that this is the good thing about putting a function for this solution.. – quantdev Jun 09 '14 at 05:07
  • Absolutely; using an `is_prime()` function is very important to keeping the solution readable. So, too, is testing `scanf()`'s return value. – Jonathan Leffler Jun 09 '14 at 05:10
  • Thank you, sorry for not being that clear on what i wanted on the tittle. However, after a few editing, this code works perfectly on what i wanted. – user3348699 Jun 09 '14 at 05:36
  • @quantdev After checking if it is divisible by 2 and 3 you can increase the counter by 2 every loop iteration, because every even number is divisible by two so the tested number was already divisible by two. So: check if divisible by two, then start the forloop by 3 and increase by 2 every iteration. – Simon Jun 09 '14 at 11:00
1

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
sir psycho sexy
  • 780
  • 7
  • 19
1

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Parth Sane
  • 587
  • 7
  • 24
1

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
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • This doesnt work. OP want the average of the prime numbers, not the overall average. – quantdev Jun 09 '14 at 04:57
  • Check out my answer it gets the average of only the prime numbers in the array as you want. Pls upvote and accept it if you like it. – Parth Sane Jun 09 '14 at 05:08
  • my apologies, I originally interpreted "After that, I'm doing the average of the values" to mean doing an average of all of the values. Fixed. – David C. Rankin Jun 09 '14 at 05:22