dev.css dev.css - 18 days ago 8
Java Question

Java - Print 5 prime numbers in a row

My project is to print prime numbers between 0 and 100, but also display 5 of the prime numbers per row.

//Print first 100 Prime numbers.

for (i = 1; i <= 100; i++) {

int counter=0;

for(num =i; num>=1; num--) {
if(i % num == 0) {
counter = counter + 1;
}
}

if (counter == 2) {
//Display the output of 5 numbers per row.
System.out.print(" " + i);
if(i % 5 == 1) {
System.out.print("\n");
}
//Prime number is assigned to the empty string class variable.
displayPrimes = displayPrimes + i + " ";
}
}


Output of prime numbers works fine, Im just struggling to get them assign to 5 values per row.

The current output looks like this:


The 0-100 Prime numbers are:

2 3 5 7 11

13 17 19 23 29 31

37 41

43 47 53 59 61

67 71

73 79 83 89 97


This is the code that is meant to adapt 5 values per row.

//Display the output of 5 numbers per row.
System.out.print(" " + i);
if(i % 5 == 1) {
System.out.print("\n");
}

Answer

Simply add one more int variable to count how many prime numbers have been printed for each row. When it prints 5 numbers in a row, it goes to the next line and then resets the counter(sets the variable to 0). Like this:

int count =0;
for (i = 1; i <= 100; i++) {

        int counter=0;    

        for( num =i; num>=1; num--)
        {
        if(i % num == 0)
    {
        counter = counter + 1;
            }
        }
        if (counter == 2)
        {
            //Display the output of 5 numbers per row.
          System.out.print(" " + i);
          count++;
          if(count == 5) {
              System.out.print("\n");
              count = 0;
          }
     //Prime number is assigned to the empty string class variable.
     displayPrimes = displayPrimes + i + " ";
        }
   }