- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to output fixed number of array elements in a line
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
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,
- Related Articles
- Java Program to sort a subset of array elements
- Java Program to fill elements in a float array
- Java Program to fill elements in a short array
- Java Program to fill elements in a char array
- Java Program to fill elements in a long array
- Java Program to fill elements in a byte array
- Find Number of Array Elements Smaller than a Given Number in Java
- Unpack elements of a uint8 array into a binary-valued output array in Numpy
- Java program to print all distinct elements of a given integer array in Java
- Extract string vector elements up to a fixed number of characters in R.
- C# Program to skip a specified number of elements of an array
- Java Program to Print the Elements of an Array
- Java program for Multiplication of Array elements.
- Java Program to fill elements in an int array
- Java Program to generate random elements from a given array

Advertisements