Emmanuel Ekweanua wrote:Ok. Just coming to understand __A_V_.length is the array length.
2) If x = 0, what does ++x evaluate to? The x++ equates to 1
3) How many times does the for loop run? Based on the condition, x++<__A_V_.length. It looped just once, because if it did the second time, it will negate the for condition of 1(no of loop)<2(length of array)
Mike has been doing a terrific job of guiding you (have a cow btw), and I don't mean to butt in, but I can't resist, so here goes.
a major source of confusion for you may be the pre-increment operator (++x); you don't seem to differentiate between it and the post-increment operator (x++).
The difference between them is subtle, yet important. The pre-increment operator increases the value of the operand (x in this example) by 1 and the value of the expression is that newly incremented value. With the post-increment operator on the other hand, while the operand is also incremented, the value of the expression is equal to the old value of the operand - before it was incremented. These two simple programs highlight the difference - they are both identical except for the increment operator, and they produce different outputs.
In both programs x
starts out at 0. The PreIncrement program shows that when the pre-increment operator is used the new value of x
- 1 - is immediately available when the expression is evaluated. The PostIncrement program shows that this is not the case when the post-increment operator is used, but the second print statement proves that x has indeed been incremented
The for-loop in the code you posted basically reads as: start out with x
at value 0, for each iteration immidiately increment x
by 1 and check if that newly incremented value is smaller than the length of array __A_V_
, if it is execute the body statement, and at the end of that iteration there's nothing else to do before the next iteration - no increment expression.
If you assume you run the program with arguments "- A", then the length of array __A_V_
will be 2, with value "-" at index 0 and value "A" at index 1. The String $
starts out as an empty value. In the first iteration of the loop x
is incremented to 1 during evaluation of the termination expression. As 1 is smaller than 2, the body statement is executed and String $
is appended with value "A", which is the value at index 1 of array __A_V_
. The first iteration completes, there's no increment expression, the value of x
remains 1. The second iteration starts and the termination expression increments x
to 2, and as 2 is not smaller than 2 the loop exits immidiately without running the body statement.
What do you suppose would happend if you changed the pre-increment operator in the loop's termination expression to a post-increment operator? Try figuring it out first, then change the program and run with the same arguments as before and see what happens.