Computer Science, asked by majhirajeswari31, 5 months ago

write a JavaScript program to accept any 50 numbers and print their sum and average.​

Answers

Answered by dsouzakylee09
0

Answer:

Explanation:

/*

** Method to Find Sum of N Numbers

*/

function findSum(n) {

 let result = 0;

 for(let i = 1; i <= n; i++) {

   result = result + i;

 }

 return result

}

let n = 10;

console.log(`Sum of numebers from 1 to ${n} is ${findSum(n)}`)

Copy

 

As seen in the above, you iterated from 1 to number N and added the numbers to get the sum. The problem with the above implementation is that as the number gets bigger, so does the number of iterations.

Mathematical Approach To Find Sum Of N Numbers

Using a mathematical approach to find the sum of N numbers may completely remove the use of for loop. Let’s try to address the above problem from a mathematical approach.

The problem that you are trying to solve is :

1 + 2 + 3 + 4 + 5 + 6 + …….. + n

Let’s assume the sum of the above series to be sum.

sum = 1 + 2 + 3 + 4 + 5 + 6 + …….. + n      ——— eq-1

Now let’s reverse the series, and add the numbers backwards which will also give the same sum.

sum = n + (n-1) + (n-2) + (n-3) + (n-4) + ……. + 1     ——- eq-2

Let’s add the above eq-1 and eq-2 equations.

2(sum) = (n+1) + (n+1) + (n+1) + (n+1) + ……. (n+1)

2(sum) = n times (n+1)

sum = (n times (n+1)) / 2

You can use the above formula to find the sum of N numbers. Now let’s write the JavaScript program which implements the above formula.

function findSumWithFormula(n) {

 return (n * (n + 1)) / 2  

}

let n = 10;

console.log(`Sum of numbers from 1 to ${n}

Similar questions