JavaScript Loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

JavaScript Loop

Hello, I am working on a program and I am almost done, the problem I am encountering is that I cannot come to a way that from every 3 sandwiches the first two cost 3.50$ and the third 2$. How can I make a loop to do this. if I want to see the total cost of 10 sandwiches.

30th May 2019, 8:29 PM
Isaac
Isaac - avatar
2 Answers
+ 4
I'm not sure if I fully understood your question, but maybe this can give you an idea: var totalCost = 0; for(var sandwich = 1; sandwich <= 10; sandwich++) { if(sandwich % 3 == 0) { console.log("$2 -> sandwich " + sandwich); totalCost += 2; } else { console.log("$3.50 -> sandwich " + sandwich); totalCost += 3.50; } } console.log("Total cost: " + totalCost);
30th May 2019, 8:52 PM
Ipang
+ 3
for(var i = 0; i<= 10; i++){ if(i%3!=0){ console.log(i+"this first and second one cost 3.50
quot;); } if(i%3==0){ console.log(i+"this third one cost 2
quot;); } }
30th May 2019, 8:58 PM
Valencia
Valencia  - avatar