r/javahelp • u/[deleted] • Feb 21 '20
Finding every 5th number between 0-50 using for loops?
I’m brand new to java and we started recently learning loops. I’m incredibly confused by how to find every 5th number and have been working on this particular problem for hours. Please help :(
13
u/ZukoBestGirl Feb 21 '20
I could give you some of the "smart answewrs"
for (int i = 0; i <= 50; i+=5) {
System.out.println(i);
}or
for (int i = 0; i <= 10; i++) {
System.out.println(i*5);
}then I'll give you the bad answer, that still works
for(int i = 0; i <= 50; i++){
if(i%5 == 0){
System.out.println(i);
}
}And let you figure out why.
6
u/tremblinggigan Feb 21 '20
Would the first 5th number be 4 or 5?
You can either increase your step (the 3rd parameter of the for loop) or you could have a variable keep track of which loop it's in after the last fifth number.
I.e. This is the first loop, this is the second loop...we're at the fifth loop: do a thing and reset the variable, this is the first loop etc.
5
u/poornbroken Feb 21 '20
I would maybe try the Modulo operator, then adjust... if you’re starting at 0 or 1...
3
u/huntsvillian Feb 21 '20
Was might first thought as well, but... it sounds like he wants every fifth number, which i'd expect to be something like... 4,9,14. (starting at zero) I suppose starting at 1 that would work.
-8
u/spaceweed27 Feb 21 '20
What you could so is this:
for(int I=0, I<50, I++){
If(i%5==0){
System.out.println("Number: "+ I);
}}
In this code he is always dividing with 5, but when it is a multiplicator of 5 it will print it out
0
Feb 21 '20
[deleted]
12
u/PhantomOTOpera Feb 21 '20
I think there is a better teaching opportunity here if we encourage the use of changing what i is incremented by rather than using the modulo operator. The solution is way simpler and you learn about how for loops work
13
u/[deleted] Feb 21 '20
How much do you understand for loops? Could you answer the same question except find every number 0-50?