for loop into while loop
likeray (0)

help, cannot turn for loop into a while loop.

for works well, just need to make an equivalent while

You are viewing a single comment. View All
mwilki7 (545)

Here is a for loop from your code:

for(i=0; i < numOfRolls; i++)
{
    ...
}

Here is a while loop equivalent:

var i = 0;
while (i < numOfRolls)
{
    ...
    i++;
}
likeray (0)

I plugged those in verbatim and the page doesn't return anything functional @mwilki7, any help would be appreciated. super noob in the house

likeray (0)

re wrote to look like such and nothing happens @mwilki7

<script type ="text/javascript">
function roll(numOfRolls)
{
// Initalize function variables and a history array
var i=0;

while (i < numOfRolls)
{
r=RandomInt(1, 6);
rollHist[r-1]++; // rollHist[r] value is incremented
totals+=r i++; // add the value or r to the totals
} // end of for loop

var avg = totals / numOfRolls; // calc the average from the total

document.form1.average.value=avg; // update the text box
// update the roll hits history display
while (c<6)
document.form1.rollHistory[c].value=rollHist[c];
} // end of function roll
mwilki7 (545)

@likeray

while (i < numOfRolls)
{
r=RandomInt(1, 6);
rollHist[r-1]++; // rollHist[r] value is incremented
totals+=r i++; // add the value or r to the totals
} // end of for loop

should be
while (i < numOfRolls)
{
r=RandomInt(1, 6);
rollHist[r-1]++; // rollHist[r] value is incremented
totals+=r; // add the value or r to the totals
i++;
} // end of for loop

likeray (0)

thank you I plugged in and it looked like this, however, still getting all 0s

<script type ="text/javascript"> function roll(numOfRolls) { // Initalize function variables and a history array var i=0; while (i < numOfRolls) { r=RandomInt(1, 6); rollHist[r-1]++; // rollHist[r] value is incremented totals+=r i++; // add the value or r to the totals } // end of for loop should be while (i < numOfRolls) { r=RandomInt(1, 6); rollHist[r-1]++; // rollHist[r] value is incremented totals+=r; // add the value or r to the totals i++; } // end of for loop </script>

@mwilki7

mwilki7 (545)

@likeray
On a sandbox, here is my input, and the corresponding output:

var i = 0;
var j = 0;

var count = 5;

for (i = 0; i < count; i++)
{
  console.log("i is: " + i);
}

while (j < count)
{
  console.log("j is: " + j);
  j++;
}

Output:

'i is: 0'
'i is: 1'
'i is: 2'
'i is: 3'
'i is: 4'
'j is: 0'
'j is: 1'
'j is: 2'
'j is: 3'
'j is: 4'
likeray (0)

any way you can give me the full html for this, super new, old man to the community here. thank you in advance for any consideration @mwilki7

mwilki7 (545)

@likeray no problem
sometimes javascript does weird stuff without telling you like how 'i' isn't defined anywhere and it will still let you set it equal to stuff

this seems to be working from my end
https://repl.it/@mwilki7/equivalent-while-loop-needed
let me know if it doesn't work

likeray (0)

perfection, thank you kind sir!!! @mwilki7