Challenge #4
Udemy Javascript Fundamentals part 2
by trentHarlem
HTML
<h2>
Coding Challenge #4
</h2>
<p>
Let's improve Steven's tip calculator even more, this time using loops!<br>
1. Create an array 'bills' containing all 10 test bill values<br>
2. Create empty arrays for the tips and the totals ('tips' and 'totals')<br>
3. Use the 'calcTip' function we wrote before (no need to repeat) to calculate tips and total values (bill + tip) for every bill value in the bills array. Use a for loop to perform the 10 calculations!<br>
</p>
TEST DATA: 22, 295, 176, 440, 37, 105, 10, 1100, 86 and 52<br>
HINT: Call calcTip in the loop and use the push method to add values to the tips and totals arrays 😉<br>
<p>
4. BONUS: Write a function 'calcAverage' which takes an array called 'arr' as an argument. This function calculates the average of all numbers in the given array. This is a DIFFICULT challenge (we haven't done this before)! Here is how to solve it:<br>
4.1. First, you will need to add up all values in the array. To do the addition, start by creating a variable 'sum' that starts at 0. Then loop over the array using a for loop. In each iteration, add the current value to the 'sum' variable. This way, by the end of the loop, you have all values added together<br>
4.2. To calculate the average, divide the sum you calculated before by the length of the array (because that's the number of elements)<br>
4.3. Call the function with the 'totals' array<br>
</p>
GOOD LUCK 😀
CSS
html{
font: 1.1em system-ui;
}
JavaScript
const bills = [22, 295, 176, 440, 37, 105, 10, 1100, 86, 52]
const tips = []
const totals = []
const calcTip = bill => {
if (bill >= 50 && bill <= 300) {
tip = bill * 0.15
totals.push(bill+tip)
return tip
} else {
tip = bill * 0.20
totals.push(bill+tip)
return tip
}
}
for (let i = 0; i < bills.length; i++) {
tips.push(calcTip(bills[i]))
}
//tried adding loop to existing function
/* const calcTips = arr => {
for (let i = 0; i < arr.length; i++) {
let bill = arr[i]
if (bill >= 50 && bill <= 300) {
tip = bill * 0.15
totals.push(bill + tip)
tips.push(tip)
} else {
tip = bill * 0.20
totals.push(bill + tip)
tips.push(tip)
}
}
} */
//calcTips(bills)
console.log(tips)
console.log(totals)
function calcAverage(arr) {
let sum = 0
for (let i = 0; i < arr.length; i++) {
sum += arr[i]
}
console.log(sum / arr.length)
return sum / arr.length
}
calcAverage(totals)