Link to home
Start Free TrialLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

How would I do this in a Javascript loop?

I have to write a program / function  that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five, I've got to print "Buzz". For numbers which are multiples of both three and five, I've got to  print "FizzBuzz".

How?
Avatar of Randy Poole
Randy Poole
Flag of United States of America image

Use the modulus operator to see if your loop variable has a remainder
<html>
<head>
<script language="javascript">
	function doloop()
	{
		var c1,c2,r,o;
		o="";
		for (var c=1;c<=100;c++)
		{
			r="";
			c1=c % 3;
			c2=c % 5;
			r+=((c % 3)==0)?"Fizz":"";
			r+=((c % 5)==0)?"Buzz":"";
			r=r==""?(c):r;
			o+=r+"<br />";
		}
		document.getElementById("output").innerHTML=o;
	}
</script>
<head>
<body onload="doloop();">
	<div id="output">
	</div>
</body>
</html>

Open in new window

Avatar of gplana
Try this:

<html>
<body onload="doloop();">
<script language="javascript">
		var c1,c2,r,o;
		for (var i=1;i<=100;i++)
		{
			if (i%15==0) document.write('FizzBuzz<br />')
                        else if (i%5==0) document.write('Buzz<br />')
                        else if (i%3==0) document.wirte('Fizz<br />');
                        else document.write( i + '<br />');
		}
</script>

</body>
</html>

Open in new window


Hope it helps.
ASKER CERTIFIED SOLUTION
Avatar of gplana
gplana
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Bruce Gust

ASKER

Excellent!