Some for Loop Variations Java Help

Some for Loop Variations

The for loop  a number of variations that increase its power and applicability. The reason it is so flexible is’that its three parts, the initialization, the conditional test, and the iteration, do not need to be used for only those purposes. In facl, the three. sections of the for can be used for you desire. Let’s look at some ex-amp les.One of the most common variations involves the conditional expression. Specifically, this expression does not need to test the loop control variable against some target value. In fact,  condition controlling the for can be any Boolean expression: For example,’ consider the following fragment.

In this example, the for loop continues to run until the boolean variable done is set to
true. It does not test the value of i. Here is another interesting for loop variation. Either the initialization or the iteration expression or both may be absent, as in this next program.

Here, the initialization and iteration expressions have been moved out of the Eor. Thus, parts of the for are empty. While this is of no value in this simple example-Indeed, it would be considered qttite poor style-there can be times when this type of approach makes sense. For example, if the initial condition is set through a complex expression elsewhere in the program or if the loop control variable changes in a non sequential manner determined by actions that occur within the body of the loop, it may be appropriate to leave these parts of the for empty. Here is one more for loop variation. You can intentionally create an infinite loop (a loop that never terminates) if you leave all three parts of the for empty. For example:

JavaHelpOnline.com

  • Feel free to send us an inquiry, we will reply back in hours.
 

Verification

Posted on September 17, 2014 in The Complete Reference

Share the Story

About the Author

Back to Top