Java Beginner: Lesson 7

for loop


After showing the while and do while loops in the previous lessons we will see the for loop in this lesson. We will see 2 types of implementation of the for loop in this lesson. The first way to implement the for loop, an unusual one, is the one shown bellow, editing the code of the previous lessons to replace do while with for to keep the same functionality we get:

Example code:

As you can see, the for loop has a structure different from the while and do while loop, it takes in the rounded brackets 3 expressions and not 1. In the example shown above we have filled only one expression and left blank the other 2. As I mentioned above this is an unusual implementation of the for loop. Bellow is shown a clasic implementation of the for loop.

Example code:

The above example code is modified from the previous example in order to get the number of the repetitions from the user. This is the complete form of for loop:
for( int i=0 ; i< repetitions ; i++ ){
where the first expression declares a new variable of type int, the second expression is a boolean expression, this expression determines how many times will be executed the part of code within the curly brackets. As long as the expression will evaluate true the code will be executed. The last expression determines the incrementation step of the variable.

In the figure 1 bellow is shown the execution of the above code. In the case of the shown test the value of the repetitions variable is set to 2 and the code is executed exactly 2 times.



(please report broken link in the comment)

Comments

Popular posts from this blog

Free host and domain

C++ Beginner: Lesson 3 - Simple calculator

C++ Beginner: Lesson 4 - Tic Tac Toe game