Printing the elements of an array with 10 elements on each line
I just created an array with 100 initialized values and I want to print 10 elements on each line so that it is something like this
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16
...26
this is the code i used and i managed to do it for the first 10 elements but i couldnt figure out how to do it for the rest
public static void main(String[] args) {
int[] numbers = { 0,1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};
int i, count = 0;
for (i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 9)
for (i = 9; i < numbers.length; i++)
System.out.println(numbers[i] + " ");
}
}
a source to share
int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
if (i % 10 == 0 && i > 0) {
System.out.println();
}
System.out.print(numbers[i] + " ");
}
This prints a new line before printing numbers[i]
where i % 10 == 0
and i > 0
. %
- mode operator; it returns the remainder if i / 10
. So i % 10 == 0
when i = 0, 10, 20, ...
.
As far as the source code is concerned, you can make it work with a slight modification like this:
int count = 0;
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
Basically, count
how many numbers you typed on that line. Once it reaches 10, you will print a new line and then reset back to 0 because you are starting a new line and you haven't printed any numbers for that line yet.
Note that in the above two solutions, extra space is printed at the end of each line. Here's a more flexible implementation that only uses separators (horizontal and vertical) when needed. This is a little tricky.
static void print(int[] arr, int W, String hSep, String vSep) {
for (int i = 0; i < arr.length; i++) {
String sep =
(i % W != 0) ? hSep :
(i > 0) ? vSep :
"";
System.out.print(sep + arr[i]);
}
System.out.println(vSep);
}
If you say it like print(new int[25], 5, ",", ".\n");
, then it will print 25 zeros, 5 on each line. At the end of each line, there is a period ( .
) and a comma ( ,
) between the zeros in the line.
a source to share
Why are you using 2 nested loops where you only need to remember where you need to output the string? Also using the same variable i
for both loops won't do what you expect.
What about:
for (i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 10)
System.out.print("\n");
count = 0;
}
}
a source to share