- 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,
Advertisements
To Continue Learning Please Login
Login with Google