parisr lover
parisr lover

Reputation: 1

how to print divisibles of a number in separate lines?

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?

Upvotes: 0

Views: 128

Answers (3)

Md. Kabir Hassan
Md. Kabir Hassan

Reputation: 21

    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

Upvotes: 0

Mohan
Mohan

Reputation: 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();
        }
    }
}

Upvotes: -1

Alex
Alex

Reputation: 591

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

Upvotes: 1

Related Questions