Reputation:
I have created an int array to hold 100 values and have initialized them to be random integer values from 1-100.
Now my task is to output this array in a 10x10 block separated by tabs.
for example:
48 49 88 ..... (until 10 numbers appear on this line)
45 1 55 ..... (until 10 numbers appear on this line)
59 21 11 ..... (until 10 numbers appear on this line)
until 10 numbers appear going down as well
I'm kind of lost on how to do this, any tips?
Upvotes: 0
Views: 138
Reputation: 41
What you have to do, is to put a a newline-sign "\n" after each 10th element and a tab "\t" after each other one
Let's say a is your array. Then you could accomplish this at example by doing:
for(int i = 1; i <= a.length; i++){
//print out the element at the i-th position
System.out.print(a[i-1])
//check, if
if(i % 10 == 0){
//you could also simply use System.out.println()
System.out.print("\n");
}else{
System.out.print("\t");
}
}
Upvotes: 1
Reputation: 1203
A for
loop is the easiest way to do this. Assuming x
is the name of your single-dimensional, 100-element int
array:
for(int i = 0; i < x.length; ++i)
{
System.out.print(x[i]);
if((i % 10) == 9)
{
System.out.print("\n");
//or System.out.println();
//both print a new line
}
else
{
System.out.print("\t");
}
}
\t
gives you a tab, \n
gives you a new line.
The (i % 10) == 9
part checks to see if you are on the 10th column. If you are, then you create a new line with the \n
character.
This will iterate to the end of the array as well and no further, so if you ended up having a different number of columns than 100, this would not run the risk of trying to access an element that does not exist.
Upvotes: 1
Reputation: 1
If you just want to print them in that maner. Use som form of while loop that prints out 10 elements with a tab between them and last element Will have a new line sign because of a If statement for 10th element. This van be done through some form of counter.
Upvotes: 0