Answer the question
In order to leave comments, you need to log in
How to transfer from a function to a loop?
I am writing a project for a coffee machine. Please help me rewrite this code for calculating change in coins from a function into a loop using while and for and output to console.log For example, if 50r is change 10 rubles by 5.
function oldgetChange(num) {
if (num >= 10) {
console.log(10);
getChange(num - 10);
} else if (num >= 5) {
console.log(5);
getChange(num - 5);
} else if (num >= 2) {
console.log(2);
getChange(num - 2);
} else if (num >= 1) {
console.log(1);
getChange(num - 1);
} else {
console.log("Вся сдача выдана!");
}
}
Answer the question
In order to leave comments, you need to log in
Such a function will return an array of the number of coins of each size, resp. 10, 5, 2 and 1:
function getChange(num) {
const coins = [10, 5, 2, 1];
return coins.map((c) => {
const n = Math.floor(num / c);
num -= n * c;
return n;
});
}
Rewrite it with a loop while
or for
. There is also a loop here: the array method iterates map()
over each of its elements, executing a function inside for the next value and replacing the element with the returned value. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question