for loop repetition control structure explained - Java tutorial for beginners
Coding River
for loop repetition control structure explained - Java tutorial for beginners
In this video, we are going to talk about for loop control structure. The for loop is a type of what we call repetition control structures In Java, there are three types of repetition control structures which are the while loop, for loop and the do … while loop In the previous videos, we talked about the while loop Now it’s high time we talked about the for loop
Here on the screen is the syntax of a for loop statement
for (int i = 0 ; i less than 10 ; i++) System.out.print(i + “ “);
Let me now explain the various elements of this statement First, we have the keyword for which is announcing that this is a for statement Inside the brackets, the first expression is called the initial expression After that is the logical expression that returns a boolean value Then, the last expression is called the update expression All these three expressions are called the for loop control expressions and they are used to control the execution of the action statements down here
Note that the for loop control expressions are separated by semicolons And also the body of the for loop can contain a simple or compound action statement
So now what happens when the for loop execute
The first expression to execute will be the initial expression int i = 0, here This expression is usually used to initialize a variable called the loop control variable The next expression to execute is the loop condition i less than 10 which is a logical expression
If this logical expression i less than 10 evaluates to true, then the action statements in the body of the loop are executed Then, after the update expression i++, here will execute
This process would continue repeatedly until the loop condition evaluates to false
As soon as the loop condition evaluates to false, then the for loop will stop executing
In our example, this program will print out 10 positive integer numbers That will be numbers from 0 to 9
When using for loop structures, you need to be extra careful in order to get the for loop to perform the desired action
The first point to note is that, if the for loop condition evaluates to false from the beginning of the loop execution, then the action statements in the body of the loop will not execute at all So, you always have to make sure that the loop condition is well written
The second point to note is that you always have to make sure to have an update expression that is used to update the value of the loop control variable. Updating the value of the loop control variable will ensure that the loop condition evaluates to false. That’s important because, if the loop condition is always true that will lead to an infinite loop, where the loop executes indefinitely
The third poi ... https://www.youtube.com/watch?v=OhT9lFzEOEM
13343605 Bytes