-3

How can I write a while loop to output the integer values from 0 up to n exclusive.

The output should have five values per line, with values separated by a space. I can do it on the same line but, I am confused about the five values per line. Where am I supposed to add while loop to do it?

import java.util.Scanner;

public class While
{
   public static void main( String[] args)
   {
      Scanner scan = new Scanner( System.in);

      // constants

      // variables
      int n;
      int value;


      // program code
      value = 0;
      System.out.println( "Enter an integer ");
      n = scan.nextInt();
      if( n <=0){
         System.out.println( "Error");
      }else
         while ( value < n){
         System.out.print( value + " ");
         value = value + 1;
      }
   }
}
Zephyr
  • 9,885
  • 4
  • 28
  • 63

3 Answers3

1

You can use the modulus operator to determine if value is a multiple of 5, and if so, print a newline:

while (value < n){
     System.out.print(value + " ");         
     if(value %5 == 4) {
          System.out.println();
     }
     value = value + 1;
}

Output: (With input of 10)

0 1 2 3 4 
5 6 7 8 9 
GBlodgett
  • 12,704
  • 4
  • 31
  • 45
0

You just need a System.out.println(); after every 5th element:

    while ( value < n){
        System.out.print( value + " ");
        value = value + 1;
        if (value % 5 == 0)
            System.out.println();
    }
forpas
  • 160,666
  • 10
  • 38
  • 76
0

This one line of code will print five values per line, with values separated by a space: System.out.print(value % 5 == 0 ? "\n" : " ");

\n is new line character. In print method \n gives a line break. So if (value % 5 == 0) equals true this line prints a line break, otherwise it prints space.

Thus your while loop should be like this:

while (value < n) {
    System.out.print(value);
    value = value + 1;
    System.out.print(value % 5 == 0 ? "\n" : " ");
}
Hülya
  • 3,353
  • 2
  • 12
  • 19