Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

1. Issue with addition in a for-loop

I'm trying to write a program that will allow users to order pizza online and enter the desired number of toppings for each pizza. I think I have the entire thing running correctly except that instead of adding the number of toppings for each pizza together to get a total number of toppings, it's just stringing them together. For example, if someone enters that they want 4 pizzas with 1, 3, 2, and 5 toppings, instead of returning a topping value of 11, it returns 5231. The function that contains this step is below...could someone please tell me where I'm going wrong and point me in the right direction? I didn't want to post too much code, but if you need more information, please reply and I can post as much of the code as you want to see. Thank you!

Code:
```function toppings()
{var pizza1 = parseFloat(document.pizza_order.pizzas.value);
var message;
var x = 1;
var i;
var topping_no;
for(i=x; i<=pizza1; i++)
{message = "Please enter the desired number of toppings for pizza " + (x=i) + "";
topping_no = parseFloat(prompt(message, "0") + topping_no);}

• Try

var i = 0;
var topping_no = 0;

to declare these variables as numbers, not strings.

• Nope, that didn't work. Now it just adds a zero to the numbers of topping that it's stringing together. Thanks for the suggestion, though.

• That shows that the variable is a string which is being concatenated.

Also try altering parseFloat to parseInt - presumably you can only have integer numbers of pizzas and toppings.

+ (x=i) Surely this is incorrect?

• Try this:
Code:
```<script language="javascript">
function toppings()
{var pizza1 = parseInt(document.pizza_order.pizzas.value);
var toppings = parseInt(topNum);
var message;
var i = 1;
var topping_no = 0;
for(i=1; i<=pizza1; i++)
{message = "Please enter the desired number of toppings for pizza " + i + "";
topping_no += parseInt(prompt(message, "0") + toppings);}
var topNum = topping_no;
</script>```

• Thank you so much, Brando, it's finally working!

• You're welcome...glad you got it working

•

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•