This tutorial we will be learning more about the for loop in Java programming. I was thinking of positing a do-while loop before I do the for loop, however, I changed my mind as I need some time to think of a suitable example to illustrate the do-while loop. Hence, I will post up the tutorial for the for loop first.
The for loop has a slightly complicated general form as compared to the while loop. Now, the general form of the for loop looks like this: for (control variable, condition, iteration - change for the control variable) { codes to execute}. From this, you can see that there are three different things we need to define in the for loop. These three determinants are present in while loop as well, however, we may not specify them directly when we are typing the code for the loop. In while loop, we usually specify the control variable before the code of the while loop, and iteration are stated inside the body of the while loop. Note that these may not exist depending on the type of loop you are writing your code for. Now, it may be a little complicated to explain without some thing to visualize so let us take a look at an example of a for loop.
Based on the above, we can see clearly that there are three different sections within the for loop. In this case, we try to replicate the example in the while loop tutorial here. Hence, our control variable will start with 10, and we will want the loop to continue executing the code as long as the control variable is more than zero. The change that we need the control variable to adapt will the as stated x = x-1 since we are counting down in this program. You may try adding to a certain limit, it does work as well. I will leave that for your exploration.
Try running the above program, you will be able to get the same result as the while loop example we have done previously.
Here it is! Exactly the same. I guess we succeeded replicating our previous program using a different function in Java programming.
The for loop will repeat itself until the condition of the for loop returns a false value. Only then the loop would terminate and move on to the following code. I guess that is pretty much the gist of the for loop.
It will be good for us to practice using it in different cases and find the way which we can execute such loop at ease and suits our own program more.
The marks the end of this rather short tutorial of For Loop in Java programming. Stay tune for the upcoming tutorial. I will probably try to do them up during my free time next weekend since it will be a slightly longer one.
Enjoy your day everyone. Have fun and rest well before the long work week starts.
No comments:
Post a Comment