Kyle Wright Kyle Wright - 1 month ago 6
Javascript Question

while loop not working in javascript

I'm having a bit of trouble getting this code to work. I think it has something to do with the while loop. Also I'm new to JavaScript so, if you any suggestions on ways to improve the syntax or make my code more efficient it would be greatly appreciated.

how the code should work.
The user enters a cost of an item and then the amount of
money given. The program will figure out the change and the number of quarters, dimes, nickels, pennies needed for the change.

what happens when run
the two prompt boxes pop up and than I get a alert warning..

"A script on this page may be busy, or it may have stopped responding. You can stop the script now, open the script in the debugger, or let the script continue."

https://jsfiddle.net/krighty78/g44ejnbw/1/



/* The user enters a cost of an item and then the amount of
money given. The program will figure out the change and the number of quarters, dimes, nickels, pennies needed for the change.*/


var cost = prompt('please enter total cost of the item without tax');
cost = parseFloat(cost);

var moneyGiven = prompt('please enter the amount of money given');
moneyGiven = parseFloat(moneyGiven);

var tax = 0.15;
tax = (cost * tax);

var quarter = 0;
var dime = 0;
var nickel = 0;
var penny = 0;

var q = 0.25;
var d = 0.10;
var n = 0.05;
var p = 0.01;
var change = (moneyGiven - (cost + tax));
console.log(change);

while (change > 0) {

if (change >= q) {
change - q;
quarter++;
} else if (change >= d) {
change - d;
dime++;
} else if (change >= n) {
change - n;
nickel++;
} else if (change >= p) {
change - p;
penny++;
}

}; //while loop

console.log(quarter);
console.log(dime);
console.log(nickel);
console.log(penny);




Answer

The while loop is OK, the problem is in the statements

change - q;
change - d;
change - n;
change - p;

You are not updating the value of change. Change these to:

change = change - q;
change = change - d;
change = change - n;
change = change - p;
Comments