• Post Reply Bookmark Topic Watch Topic
  • New Topic

loop  RSS feed

 
Andrew Concilio
Ranch Hand
Posts: 30
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
wonder if you guys could help me out.
I need to write a loop from 1 to 20 where every multiple of 3 will print "fizz" instead of the number and every multiple of 5 will print "buzz" giving me the below output.
thanks

1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
buzz
16
17
fizz
19
buzz
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Well, if I had to write a loop, I would at least try it.
What have you tried so far, where did you get stuck?



 
Andrew Concilio
Ranch Hand
Posts: 30
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the simple loop

int I ;
for (I =0; I <=20; I++)
{
System.out.print(I);
}

but my problem is how do I convert the multiples of 3 and 5 into "fizz" and "buzz"
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Andrew Concilio wrote:but my problem is how do I convert the multiples of 3 and 5 into "fizz" and "buzz"

Right, well the first thing to do is not to worry about everything at once.

First: How do you work out whether a number (actually an integer) is an exact multiple of 3? Forget about 5 for the moment; and forget about "fizz" and "buzz".

If I give you a number - say 17 - do you know how to work out whether it divides by 3?

Answer that, and then we can take it further. (Hint: you might want to look at the '%' operator)

Winston
 
Ashish Dutt
Ranch Hand
Posts: 172
Java MySQL Database Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Solving a problem is easier if you break it into parts. The code that you have posted will print numbers from 1 to 20. According to your question "you need to write code for multiples of 3 and 5". Andrew, concentrate on the bold part. You got to think how in mathematics, you can make multiples of 3 and 5. A clue for you is that division is the reverse of multiplication. Also you will find the 'modulus operator' in programming to be interesting.
Hope this helps.
 
Andrew Concilio
Ranch Hand
Posts: 30
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Winston and Ashish for your help, I came across to my answer by accident and it turned out that I wasn't the only one. it look like this is a classic entry level java interview question here is the link
http://stackoverflow.com/questions/10466709/fizzbuzz-print-string-depending-on-number
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!