HenryDev
HenryDev

Reputation: 4953

Looping though an array in java spliting the elements

So I have an array in java that looks like this:

int[] theArray = {2,3,6,9,10,12,17,16,18,20,23,24,28,30,31};

Desired output:

2  3  6  9  10
12 17 16 18 20
23 24 28 30 31

Upvotes: 2

Views: 94

Answers (3)

Alex
Alex

Reputation: 6376

So, basically you want to output the values in an array with a newline after every fifth element? You can use the modulo operator to achieve that.

In (untested) code:

for (int i = 0; i < arrayWithNumbers.length; i++)
{
    if (i % 5 == 0 && i != 0) // end of the line
    {
        System.out.println(arrayWithNumbers[i]);
    }
    else
    {
        System.out.print(arrayWithNumbers[i]);
    }
}

Upvotes: 1

Zion
Zion

Reputation: 753

for(int i =0;i<theArray.length;i++)
{
if(i%5==0 && i!=0)
{System.out.println();
}
System.out.print(theArray[i]+" ");
}

Upvotes: 1

DesirePRG
DesirePRG

Reputation: 6378

All you have to do is go through the array one by one, and use System.out.print to print the elements for each set of 5 elements. Once you have printed 5 elements, do a system.out.println("");

Upvotes: 1

Related Questions