1. To find the average of all even numbers btw the given range. 2.To find the average of all odd nos btw the gven rng | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

1. To find the average of all even numbers btw the given range. 2.To find the average of all odd nos btw the gven rng

help program

21st Sep 2017, 5:07 PM
Chinmoy
Chinmoy - avatar
2 Answers
+ 4
Prepare some variables, the sum, the average, and the sample counter. Setup a for loop, starting from the lowest, until the largest number in the range. Inside the loop use a modulo operator to verify whether if a number is fully divisible by two, when there's a remainder, it's an odd number, otherwise it's even. Depending on either working for the even or the odd number: Increment the sample counter variable, Add the number to the sum variable. Finally, after the loop finished, divide the sum variable with the sample counter variable, then you get your average. Hth, cmiiw
21st Sep 2017, 5:34 PM
Ipang
+ 3
/* All even number are equivalent to all number times 2 in half range: 2, 4, 6, ... n, n+2 is same as: 1*2, 2*2, 3*2, ... ((n/2)-1)*2, (n/2)*2 Average of set of number is computed by sum them and dividing result by count, so (with N is count of items in range, so for range [1,n] N = int(n/2)): avg_even = ( 1*2 + 2*2 + 2*3 + ... + ((n/2)-1)*2 + (n/2)*2 ) / (N/2) = 4 * ( 1 + 2 + 3 + ... + (n/2)-1 + (n/2) ) / N For odd numbers, just add one to formula giving items: term = (n*2)+1 if starting iteration from 0, substract if starting from 1... avg_odd = ( (1*2-1) + (2*2-1) + (3*2-1) + ... + ((n/2)-1)*2-1) + ((n/2)*2-1) ) / (N/2) = ( 4 * ( 1 + 2 + 3 + ... + (n/2)-1 ) / N ) - 1 Implement them with a simple loop and basic factorization (pseudo-code): */ // basic (normal) average function: function avg(N) { sum = 0; for (n=1; n<=N; n++) { sum += n; } return sum/N; } // even average function implementations: function even_avg__(N) { N = (N%2==1) ? --N/2 : N/2 ; sum = 0; for (n=1; n<=N; n++) { sum += 2*n; } return sum/N; } // or: function even_avg_(N) { N = (N%2==1) ? --N/2 : N/2 ; sum = 0; for (n=1; n<=N; n++) { sum += n; } return 2*sum/N; } // then: function even_avg(N) { N = (N%2==1) ? --N/2 : N/2 ; return 2*avg(N); } // odd average function implementations: function odd_avg__(N) { N = (N%2==1) ? ++N/2 : N/2 ; sum = 0; for (n=1; n<=N; n++) { sum += 2*n - 1; } return sum/N; } // or: function odd_avg_(N) { N = (N%2==1) ? ++N/2 : N/2 ; sum = 0; for (n=1; n<=N; n++) { sum += n; } return (2*sum/N) - 1; } // and finally: function odd_avg(N) { N = (N%2==1) ? ++N/2 : N/2 ; return 2*avg(N) - 1; }
22nd Sep 2017, 8:33 AM
visph
visph - avatar