"If the operator" constantly "checks the multiplicity for the loop index index

I have a for loop that checks every fifth position. And at every fifth position I perform this action (which works):

for(int i = 0; i < foo().length; i++) { System.out.print(i); if(i == 5 || i == 10 || i == 15) System.out.println(); } 

Is there a way to write an if statement, no matter how long foo().length , I don't need to return to configure it?

+4
source share
4 answers

Use the modulus(%) operator modulus(%) : -

 if (i % 5 == 0) { } 
  • 5 % 5 == 0 , 10 % 5 == 0 , ...

Since you are using for loop , you can simply change your increment from i++ to i += 5 and leave the if condition.

 for (int i = 0; i < someNum; i += 5) { // No need to check for `i` against `modulus 5`. } 
+8
source

You can use the following for witout if

 for(int i = 0; i < foo().length; i+=5) { 

adding 5 to i step by step

+2
source

Use the following:

 if ( i % 5 == 0 ) 
+1
source

if you want to put it in one print statement, this will work too.

 for(int i = 0; i < foo().length; i++) { System.out.printf("%d%s", i, (i%5==0) ? "\n" : ""); } 
0
source

Source: https://habr.com/ru/post/1445706/


All Articles