Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 88
  • Last Modified:

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?
0
brucegust
Asked:
brucegust
  • 2
1 Solution
 
Randy PooleCommented:
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

0
 
gplanaCommented:
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.
0
 
gplanaCommented:
Sorry, a couple of errors on my script. Here is the file with the errors solved.
prova2.html
0
 
brucegustPHP DeveloperAuthor Commented:
Excellent!
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now