HerdingDogRescuer HerdingDogRescuer - 2 months ago 5
Java Question

Why are 2 for loops needed in this program?

Why does this program need 2 for loops to function? Is there a way to write this without the 2 for loops?

Its purpose is to assign integer values 1-25 to an array with a length of 25. It then prints the array as five separate lines each containing five array elements separated by commas.

Its output is this:

1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
16,17,18,19,20
21,22,23,24,25




public class ArrayNums
{
static int[] arrayList = new int[25];

public static void main(String[] args)
{

for(int i=0; i<25; i++)
arrayList[i] = i + 1;
printArray();
}

public static void printArray()

{
int i;
for(i=1; i<=25; i++){
if (i % 5 != 0)
System.out.print(arrayList[i-1]+",");
else
System.out.println(arrayList[i-1]);
}
}
}

Answer

Of course, the main function would go like this :

public static void main(String[] args)
{
    for(int i=0; i<25; i++){
       arrayList[i] = i + 1;   
       if ((i+1) % 5 != 0)
            System.out.print(arrayList[i]+",");
        else
            System.out.println(arrayList[i]);
    }
}

Though, it's considered better practice to have one function doing only one thing at a time. It makes it much easier to understand, hence your first version I would rather advice to use.

Comments