Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use array element as termination in for loop

Tags:

java

Please explain this loop:

for(p=0;p<a[j];p++)

I am a beginner and I am confused how do such loops work?

Please emphasize on use of a[j] in loop.

like image 602
P3M Avatar asked Jul 02 '11 14:07

P3M


2 Answers

If a[j] remains a constant positive number through each iteration of the for loop, the loop will run exactly a[j] times, where a[j] evaluates to some integer (or long, we can't tell from the code posted). Of course a[j] (or j) could be modified inside the loop. In any case, the loop terminates once p is greater than or equal to a[j] when the loop condition is evaluated. The condition is checked before each iteration of the loop. If a[j] is zero or a negative number, the contents of the for loop are never executed. The loop can also exit prematurely at any time if there is a call to break or return within the loop.

like image 71
Asaph Avatar answered Oct 07 '22 02:10

Asaph


You're obviously a beginner, so I'll lay it out.

The variable a holds an object that is an array of int, and j is an int. The code that preceded this snippet probably looked something like this:

int j = 5; // for example
int[] a = new int[10]; // An array of 10 ints
a[5] = 3; // somewhere, the jth element of a should have been assigned

Within this context, a[j] is 3, so the loop would initially be the same as:

for (p=0; p<3; p++)

The reason I say "initially" is that code within the loop may alter a[5] and thus change the loop termination condition to a number other than 3

Note to nitpickers: for "int" you may read any of the java numeric primatives.

like image 42
Bohemian Avatar answered Oct 07 '22 02:10

Bohemian