Java Program to output fixed number of array elements in a line

Java 8Object Oriented ProgrammingProgramming

To output fixed number of array elements in a line, we should check for a condition and if that is true, we should place System.out.println(); properly to get a line and the process goes on.

Here, we will display 5 elements in a line. At first, create a new integer array and add some elements −

int[] list = new int[50];
for (int i = 0; i < list.length; i++) {
   list[i] = (int)(i + 20);
}

Now, declare a new variable and initialize it to 0. This variable is checked in a for loop that loops until the length of the array. A new line is set after 5 elements are displayed −

int output = 0;
for (int i = 0; i < list.length; i++) {
   if (output == 5) {
      System.out.println();
      output = 0;
   }
   System.out.print(list[i] + ", ");
   output++;
}

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      int[] list = new int[50];
      for (int i = 0; i < list.length; i++) {
         list[i] = (int) (i + 20);
      }
      int output = 0;
      for (int i = 0; i < list.length; i++) {
         if (output == 5) {
            System.out.println();
            output = 0;
         }
         System.out.print(list[i] + ", ");
         output++;
      }
   }
}

Output

20, 21, 22, 23, 24,
25, 26, 27, 28, 29,
30, 31, 32, 33, 34,
35, 36, 37, 38, 39,
40, 41, 42, 43, 44,
45, 46, 47, 48, 49,
50, 51, 52, 53, 54,
55, 56, 57, 58, 59,
60, 61, 62, 63, 64,
65, 66, 67, 68, 69,
raja
Published on 23-Apr-2019 11:35:36
Advertisements