user3649499 user3649499 - 2 months ago 9
Java Question

Do not understand how loop is determining how many asterisks to print

I am a beginner at learning Java. I have stumbled upon a problem that I can not figure out. How is the loop in the code determining how many asterisk to print out. I keep looking at this part of the code..

asterisk < myArray[counter]


Could someone please explain in the simplest of terms how this works, because every time I think of the counter, I see it as nothing but the index that it is pointing to at that time in the loop.

public class Main {

public static void main(String[] args) {

int[] myArray = {12, 7, 9, 11, 23};

System.out.println("Value Distribution");

//Start of outer for loop
for( int counter = 0; counter < myArray.length; counter++){

//Start of inner for loop
for( int asterisk = 0; asterisk < myArray[counter]; asterisk++)

System.out.print("*");

System.out.println();

}//End of outer for loop

Answer

Simply put

asterisk < myArray[counter]

Means that it's checking whether amount of asterisks is less than the value from myArray[counter].

So when you have counter = 0 You also have myArray[counter] = 12.

Which means in your inner for loop, it will print asterisks until asterisk is no longer lesser than 12. Thus, going from 0-11 will print 12 asterisks.