简体   繁体   中英

average of prime numbers program

I want to calculate the average of the prime numbers between 1 to 10 and I have written a program which is as follows:

#include <stdio.h>
int main()
{ 
    int i, j, sum = 0, count = 0;
    loop1: 
        for(i = 2; i <= 10; i++)
        {
            for(j = i - 1; j > 1; j--)
            {
                if(i % j == 0)
                {
                    goto loop1;
                }
            }
            sum = sum + i;
            count++;
        }
        printf("The avg:%d", (sum / count));
        return 0;
}

Please help me whether the program is correct.

Simple answer for you:

#include <stdio.h>

int main() {

    float sum = 0, count = 0, average;
    for(int i=2; i<11; i++){
        for(int j=2; j<=i; j++){
            if(j==i){
                sum+=i;
                count++;
            }else if(i%j==0){
                break;
            }
        }
    }
    average=sum/count;
    printf("Average = %.2f", average);

    return 0;
}

What do you mean by "Correct" ?

If correct to you means that it works: well that's easy to verify for yourself.

If correct means that you are hitting the best practices, well then, nope, you missed them I'm afraid.

goto: about the most easy of all "do not use that" signs.

A "better" approach would be to write a function that tests if a number is a prime or not.

Please ensure you do not make a habit of using goto: statements. Your program is incorrect. Here, when the statement

if(i % j == 0)

returns true, the goto: statement takes control to the beginning of the parent for loop and the loop will run from start again. This way, you will never get your desired output. As per your question, your solution is wrong. A modified approach is

#include <stdio.h>
int main()
{ 
     int i, j, sum = 0, count = 0,flag;
     for(i = 2; i <= 10; i++)
     {    
         flag=0;
         for(j = i - 1; j > 1; j--)
         {
             if(i % j == 0)
             {
                 flag=1;
                 break;
             }
         }
         if(flag==0)
         {
              sum = sum + i;
              count++;
         }

     }
     printf("The avg:%d", (sum / count));
     return 0;
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM