Home > Net >  how to print divisibles of a number in separate lines?
how to print divisibles of a number in separate lines?

Time:10-03

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 code should I use to print four numbers of those divisibles line by line?

CodePudding user response:

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

CodePudding user response:

    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

CodePudding user response:

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();
        }
    }
}
  • Related