Average of prime numbers in an array - c

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");
}

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");
}

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.

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.

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

Related

prime number finding from array,c language [duplicate]

This program is supposed to print the first x prime numbers, but I noticed that it was printing some non-prime numbers, such as 27 or 35.
I've been looking at it for hours and nothing seems to pop up. So please, if you know what's wrong, tell me.
#include <stdio.h>
int main(){
int i=0, cont=2, prim=2, quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
while(i<quant){
if(prim%cont!=0 && (cont>1 && cont<prim)){
cont++;
}
else if(prim%cont==0 && (cont>1 && cont<prim)){
prim++;
}
else if(prim%cont==0 && cont==prim){
printf("%d\n", prim);
prim++;
cont=2;
i++;
}
}
return 0;
}
UPDATE
Wow, ok, so after 7 years people still stumble upon this question.
In the last 7 years my coding ability has improved somewhat, and now I see how inefficient this program was. Just in case anyone might be trying to find the solution for this and the stumble upon this, here are three solutions much easier and better, and why they work.
Solution 1:
This first solution is very inefficient too, but it works, and is pretty simple to understand. Basically what you have to do is check if each number up to the upper limit is prime or not. To do so, just check if it is divisible by any number up to its square root.
Why its squared root? Because the square root squared is equal to the number, which means that if the number was not divisible up to its square root, it won't be divisible by any number above it, as for it to be divisible by it, it needs to multiply by a smaller number. For example, the squared root of 36 is 6, and 36 is divisible by 9, as 9*4=36. But since 9 is above 6 (which is the squared root), the number that multiplied by 9 gives us 36 is below, and as such, we have already seen that it is not prime, as we have already checked that 36 is divisible by 4. This being said, if no number below the squared root of a number is a natural dividend of the number, than that number is prime.
#include <stdio.h>
int isPrime(int num) {
for (int i = 2; i*i <= num; i++) {
if (num%i==0) {
return 0;
}
}
return 1;
}
void getPrimes(int num) {
int cont = 0;
for (int i = 2; cont < num; i++) {
if (isPrime(i)==1) {
printf("%d\n", i);
cont++;
}
}
}
int main() {
int quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
getPrimes(quant);
return 0;
}
This is inefficient as we are checking if the number is divisible by numbers that won't influence (more on this in the next solution).
Solution 2:
In this second solution, which is more elegant in my opinion, we give use to the Fundamental Theorem of Arithmetic, which states that any number greater than 1 is either a prime number itself, or can be represented by factorizing into the multiplication of prime numbers. This means that if a number is divisible by a non prime number, it is also divisible by the prime numbers that make it up, and thus we only need to check if the number in question is divisible by smaller prime numbers than itself. For this purpose, we store the prime numbers in an array.
#include <stdio.h>
void getPrimes(int num) {
int primes[num];
int cont = 1;
primes[0] = 2;
int current = primes[cont-1]+1;
while (cont < num) {
int before = current;
for (int i = 0; i < cont; i++) {
if (current%primes[i]==0) {
current++;
break;
}
}
if (before == current) {
primes[cont] = current;
cont++;
current++;
}
}
for (int i = 0; i < cont; i++) {
printf("%d ", primes[i]);
}
printf("\n");
}
int main() {
int quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
getPrimes(quant);
return 0;
}
Solution 3:
This final solution is a mix of the two above. Solution 1 checked numbers that weren't prime, having redundancy, and the solution 2 checked numbers above the square root, which can never be a dividend if the smaller numbers aren't. In this solution, we check if the number is divisible only by prime numbers below the squared root.
#include <stdio.h>
void getPrimes(int num) {
int primes[num];
int cont = 1;
primes[0] = 2;
int current = primes[cont-1]+1;
while (cont < num) {
int before = current;
for (int i = 0; (i < cont && primes[i]*primes[i] <= current); i++) {
if (current%primes[i]==0) {
current++;
break;
}
}
if (before == current) {
primes[cont] = current;
cont++;
current++;
}
}
for (int i = 0; i < cont; i++) {
printf("%d ", primes[i]);
}
printf("\n");
}
int main() {
int quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
getPrimes(quant);
return 0;
}
Comparing the execution times of each algorithm for 100 prime numbers, we obtain the following results
Algorithm 1
Algorithm 2
Algorithm 3
0.048 ms
0.068 ms
0.039 ms
Comparing to the algorithm of the original post which takes 0.599 ms, every one of these new solutions is more efficient (the worst being around 10x better), and actually calculates the real values.
Try this
#include<stdio.h>
int prime(int n)
{
int i, j, len=1, brk=0;
int list[200]={2};
for(i=2; i<=n; i++)
{
for(j=0; j<len; j++)
{
if(i%list[j]==0){
brk=1;
break;
}
else
{
brk=0;
}
}
if(brk==0)
{
list[len]=i;
len++;
}
}
for(i=0; i<len; i++)
printf("%d ",list[i]);
}
main()
{
int i, n;
scanf("%d",&n);
prime(n);
}
#PKDOJ If the series is set within 30. You can go blindly with the logic below. But nothing above that series. Adding i%11 clears the 77 as well. Not efficient
if ((i % 2) && (i % 3) && (i % 5)&&(i%7)&&(i%11))
Code:
int count = 0, quant = 5, i, j;
int flag = 0;
for(prim = 2 ; count <= quant ; prim ++) {
flag = 0;
for(j = 2; j < prim/2; j++) {
if(prim % j == 0) {
flag = 1;
break;
}
}
if(flag == 0) {
printf("%d\n", prim);
count++;
}
}
Update your code as:
while(i<quant){
if(cont<prim) {
if(prim%cont!=0) {
cont++;
} else {
prim++;
cont = 2; // restart cont
}
}
else if(prim%cont==0 && cont==prim){
printf("%d\n", prim);
prim++;
cont=2;
i++;
}
}
Simple way is to find is: if a number is not divisible by 2,3 & 5, its a prime number.
#include <stdio.h>
int main()
{
int num = 35;
int i = 5;
printf("1 2 3 5");
while (i <= num)
{
if ((i % 2) && (i % 3) && (i % 5))
{
printf(" %d",i);
}
i++;
}
printf("\n");
return 0;
}

Problem in separating the digits of an n digit number

In our computer programming class, we had to separate the digits of a 5 digit number and display them on the screen, I managed to do that but then we were asked what we would do if it was an n digit number. I managed to create a program that determined the number of digits in a number, then I thought I would add the code for the 5 digit number in this program and modify it, but the output shown is not proper.
Here is the code which produced the errored output:
#include <stdio.h>
#include <math.h>
int main() {
int entry, j, input1;
input1 = entry;
j = 1;
printf("Enter the n digit number:\n");
scanf("%d", &entry);
for (j = 1; entry > 1; j++) {
entry = entry / 10;
}
printf("The number is %d digit number\n", j);
int n, t, i;
i = 1;
while (input1 > 0) {
t = input1 / (int)pow(10, j - i);
input1 = input1 % (int)pow(10,j - i);
printf("%d ", t);
i++;
}
return 0;
}
The loop wasn't running for the second part and the output was just the digit is an n digit number (that code was working), then I changed the code so the user would input the numbers again and then it worked, here's the code for the running part:
include <stdio.h>
#include <math.h>
int main() {
int entry, j;
j = 1;
printf("Enter the n digit number:\n");
scanf("%d", &entry);
for (j = 1; entry > 1; j++) {
entry = entry / 10;
}
printf("The number is %d digit number\n", j);
int input1, n, t, i;
i = 1;
printf("Enter the %d digit number again:\n", j);
scanf("%d", &input1);
while (input1 > 0) {
t = input1 / (int)pow(10, j - i);
input1 = input1 % (int)pow(10, j - i);
printf("%d ",t );
i++;
}
return 0;
}
This code works but I have to prompt the user to input the number again.
scanf("%d", &entry);
input1=entry; // assign value to 'input1' after input 'entry' is taken

Odd integers not adding up correctly

Doing an exercise to take 5 integers from user and add up only the odd numbers. Everything adds up correctly until the last number messes everything up for some reason:
Code and Test
#include <stdio.h>
int main() {
int userNum[5];
int i;
int sum = 0;
for (i = 1; i <= 5; ++i) {
printf("Please enter number %d:\n", i);
scanf("%d", &userNum[i]);
if (userNum[i] % 2 > 0) {
sum = sum + userNum[i];
}
}
printf("The sum of all odd integers is: %d", sum);
return 0;
}
You are reading the 5 numbers into the array elements userNum[1] through userNum[5], but since array indices start at 0 in C, userNum[5] does not exist and the program has undefined behavior when it attempts to store a number beyond the end of the array. Some other variable gets modified and the output is bogus. Undefined behavior could actually have much worse consequences, such as a bogus candidate winning an election with fewer votes than his opponent :)
Here is a corrected version:
#include <stdio.h>
int main() {
int userNum[5];
int i;
int sum = 0;
for (i = 0; i < 5; ++i) {
printf("Please enter number %d:\n", i + 1);
if (scanf("%d", &userNum[i]) != 1) {
printf("invalid input\n");
return 1;
}
if (userNum[i] % 2 > 0) {
sum = sum + userNum[i];
}
}
printf("The sum of all odd integers is: %d\n", sum);
return 0;
}

summation correct for powers of 3 but wring otherwise

#include <stdio.h>
#include <stdlib.h>
int summation(int sum,int Num[],int n) {
if (n < 0) {
return sum;
} else {
printf("%d \n", Num[n]);
sum = Num[n] + summation(sum, Num, n - 1);
}
}
int main () {
int i = 0, j = 0 , k = 0, n = 0;
printf("Enter number of numbers: ");
scanf("%d", &n);
int Num[n];
while (i < n) {
//printf("Enter number %d : ", i);
//scanf("%d", &Num[i]);
Num[i] = 1;
i++;
}
int sum = 0;
sum = summation(sum, Num, n);
printf("The sum is %d \n", sum);
}
The above program runs correctly only with 3
why does it generate only results for 3,3^3, 3^9??
Please help me out here this programs runs only with powers of 3. For now i have calculated 3^1,3^3 and 3^9. For other numbers it returns a wrong value.
You neglect to return a value from the summation function. A good compiler would draw your attention to this fact.
You call summation with n equal to the size of the function, which causes this line:
sum = Num[n] + ...
to read past the end of the array.
These mistakes lead to undefined behavior, which can show odd preferences for powers of three, or anything else.

How to find the sum of Prime Numbers in C within a given range?

I'm very new to programming and I was asked to find the sum of prime numbers in a given range, using a while loop. If The input is 5, the answer should be 28 (2+3+5+7+11). I tried writing the code but it seems that the logic isn't right.
CODE
#include <stdio.h>
int main()
{
int range,test;
int sum = 2;
int n = 3;
printf("Enter the range.");
scanf("%i",range);
while (range > 0)
{
int i =2;
while(i<n)
{
test = n%i;
if (test==0)
{
goto end;
}
i++;
}
if (test != 0)
{
sum = sum + test;
range--;
}
end:
n++;
}
printf("The sum is %i",sum);
return 0;
}
It would be nice if you could point out my mistake and possibly tell me how to go about from there.
first of all, in the scanf use &range and not range
scanf("%i",&range);
Second this instruction is not correct
sum = sum + test;
it should be
sum = sum + n;
and also the
while (range > 0)
should be changed to
while (range > 1)
Because in your algorithm you have already put the first element of the range in the sum sum = 2 so the while should loop range - 1 times and not range times
That's all
OK, my C is really bad, but try something like the following code. Probably doesn't compile, but if it's a homework or something, you better figure it out yourself:
UPDATE: Made it a while loop as requested.
#include <stdio.h>
int main()
{
int range, test, counter, innerCounter, sum = 1;
int countPrimes = 1;
int [50] primesArray;
primesArray[0] = 1;
printf("Enter the range.");
scanf("%i",range);
counter = 2;
while (counter <= range) {
for (innerCounter = 1; innerCounter < countPrimes; innerCounter++) {
if (counter % primesArray[innerCounter] == 0)
continue;
primesArray[countPrimes + 1] = counter;
countPrimes ++;
sum += counter;
}
counter ++
}
printf("The sum is %i",sum);
return 0;
}
I haven't done C in a while, but I'd make a few functions to simplify your logic:
#include <stdio.h>
#include <math.h>
int is_prime(n) {
int i;
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int range, i, sum, num_primes = 0;
printf("Enter the range: ");
scanf("%d", &range);
for (i = 2; num_primes < range; i++) {
if (is_prime(i)) {
sum += i;
num_primes++;
}
}
printf("The sum is %d", sum);
return 0;
}
Using goto and shoving all of your code into main() will make your program hard to debug.
Copy - pasted from here.
#include <stdio.h>
int main() {
int i, n, count = 0, value = 2, flag = 1, total = 0;
/* get the input value n from the user */
printf("Enter the value for n:");
scanf("%d", &n);
/* calculate the sum of first n prime nos */
while (count < n) {
for (i = 2; i <= value - 1; i++) {
if (value % i == 0) {
flag = 0;
break;
}
}
if (flag) {
total = total + value;
count++;
}
value++;
flag = 1;
}
/* print the sum of first n prime numbers */
printf("Sum of first %d prime numbers is %d\n", n, total);
return 0;
}
Output:
Enter the value for n:5
Sum of first 5 prime numbers is 28
Try the simplest approach over here. Check C program to find sum of all prime between 1 and n numbers.
CODE
#include <stdio.h>
int main()
{
int i, j, n, isPrime, sum=0;
/*
* Reads a number from user
*/
printf("Find sum of all prime between 1 to : ");
scanf("%d", &n);
/*
* Finds all prime numbers between 1 to n
*/
for(i=2; i<=n; i++)
{
/*
* Checks if the current number i is Prime or not
*/
isPrime = 1;
for(j=2; j<=i/2 ;j++)
{
if(i%j==0)
{
isPrime = 0;
break;
}
}
/*
* If i is Prime then add to sum
*/
if(isPrime==1)
{
sum += i;
}
}
printf("Sum of all prime numbers between 1 to %d = %d", n, sum);
return 0;
}

Resources