Help please - for loop with if...else statement

Hello,
I’m trying to create code so when a user presses a button, X’s and O’s appear.
The x’s and o’s should work in a pattern of x, xo, xox up to 16 x’s and o’s.
I have created the button and I would like to use a for loop and an if, else statement.
I kind of understand how the for loop works but how would I use the if… else statement to do this?

Please see code in a reply below!

Thanks so much! Any help would be really really great.

<!DOCTYPE html>
<html>
<body>

<p> </p>

<button onclick="myFunction()">Generate pattern</button>

<p id="demo"></p>

<script>
function myFunction() {
	var text = "";
    var i; 
    for (i = 0; i < 10; i++) {
    	continue;
       }
       text += "X" + i + "<br>"; 
      }
      document.getElementById ("demo").innerHTML = text;
    }
    </script>
    </body>
    </html>

Using jsfiddle and click on Tidy button helps you find one problem. The other solution look at the calculation in the loop.

https://jsfiddle.net/dgcj96k8/3/

I think you’re misusing the continue statement here. It makes the computer jump to the next iteration of the loop without doing anything else. Because you have continue as the first statement of your loop, it makes your loop do nothing but count to ten.

Try this…

for (i = 0; i < 10; i++) {
  text += "X" + i + "<br>"; 
}

You also have an extra }.

1 Like

Hi Ollie, thanks so much for getting back to me!
Your code helped me get a result.

I found another way to do it, like this but I don’t think is the way it should be but it returns the correct result:

<!DOCTYPE html>
<html>
<body>

<h2></h2>

<script>
  //this is the button
function btnClick()
{
  //this is the table including the xs and os
var table = 'X <BR> XO <BR> XOX <BR> XOXO <BR> XOXOX <BR> XOXOXO <BR> XOXOXOX <BR> XOXOXOXO <BR> XOXOXOXOX <BR> XOXOXOXOXO <BR> XOXOXOXOXOX <BR> XOXOXOXOXOXO <BR> XOXOXOXOXOXOX <BR> XOXOXOXOXOXOXO <BR> XOXOXOXOXOXOXOX <BR> XOXOXOXOXOXOXOXO <BR> XOXOXOXOXOXOXOXOX <BR> XOXOXOXOXOXOXOXO <BR> XOXOXOXOXOXOXOX <BR> XOXOXOXOXOXOXO <BR> XOXOXOXOXOXOX <BR> XOXOXOXOXOXO <BR> XOXOXOXOXOX <BR> XOXOXOXOXO <BR> XOXOXOXOX <BR> XOXOXOXO <BR> XOXOXOX <BR> XOXOXO <BR> XOXOX <BR> XOXO <BR> XOX <BR> XO <BR> X';

document.getElementById("grid").innerHTML =table;
}
</script>
<body>
	<input type ="button" value ="Generate pattern" OnClick ="btnClick()">
    <div><table id="grid"</div>
    
    </body>
    </html>

That’s a lookup-table approach to solving your problem. Lookup tables can be fast, but they take a while to type and can be error prone.