Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Calculate Sums using JavaScript Create a function with JavaScript called calcula

ID: 3719888 • Letter: C

Question

Calculate Sums using JavaScript

Create a function with JavaScript called calculateSums that will accept an array of numbers, and return true if the sum of all the positive numbers is greater than or equal to the sum of the absolute value of all the negative numbers.

Method of completion
You should use a while loop in your solution.
It does not matter if you consider 0 a positive or negative number because it will not change the sum of either side.
After your loop finishes, you should simply return whether the sum of positive numbers is greater than or equal to the sum of negative numbers. It should be possible to call the function as follows:
calculateSums([-1,2]) returns true
calculateSums([-1,2,-3]) returns false
In your code, call your function several times and display the arrays used and the result on your HTML page.

Calculate Sums

Your code must include a function called calculateSums that accepts an array of numbers and includes a return statement

Your function must include a while loop.

Your code must use Math.abs() to get the absoluate value of any negative numbers.

Your code must NOT include an infinite loop.

Your code must conditionally return true or false.

Your code must include multiple variations of tests to show your function works.

Explanation / Answer

<!DOCTYPE html>
<html>
<body>

<script>

function calculateSums(a) {
var absSum =0, sum=0;
var i=0;
while(i<a.length) {
if(a[i]>=0) {
sum+=a[i];
}else {
absSum+=Math.abs(a[i]);
}
i++;
}
return sum>absSum;
}

alert(calculateSums([-1,2,-3]) );
alert(calculateSums([-1,2]) );
</script>

</body>
</html>

Output:

false

true

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote