0

In Java, I have been trying to print the divisibles of the number 5. I got them to print out, but I would like to print four numbers in each line. I am using the following to print out the numbers divided by 5.

System.out.println("\nDivided by 5: ");     

for (int i=1; i<100; i++) {
        if (i%5==0) 
        System.out.print(i +", ");          
}           
        

What should I format to print four numbers of those divisibles line by line?

  • add a counter and increment it inside the `if (i%5==0)` . if the counter reaches the desired number`println()` and reset it. – ATP Oct 02 '22 at 12:31

3 Answers3

1

You can approach this with a simple modulo-counter, that would break the line, whenever the number of prints reached four. Your code would then look similar to:

int counter = 0;
for (int i = 0; i < 100; i++) {
  if (i % 5 == 0) {
    System.out.print(i);
    if (++counter % 4 == 0) // Then break the line
      System.out.println();
    else // print the comma
      System.out.print(", ");
  }
}

Here is a similar question: How to print n numbers per line

Alex
  • 439
  • 5
  • 16
0
    import java.util.*;
    
    class MyClass{
        
    static int MyNum(int n)
    {
    
        // Iterate from 1 to N=100
        for(int i = 1; i < n; i++)
        {
    
        //operator is used
        if (i % 5 == 0)
            System.out.print(i + " ");
        }
        return n;
    }
    
    public static void main(String args[])
    {
        // Input goes here
        int N = 100;
        
        //generator function
        MyNum(N);
    }
  }

Output : 5 10 15 20

-1
int count = 0;
for(int i=0;i<100;i++){
    if(i%5==0){
        System.out.print(i+", ");
        count++;
        if(count%4==0){
            System.out.println();
        }
    }
}
Mohan
  • 1
  • 1