For Next Loop
A For Next loop is used to repeatedly execute a sequence of code or a block of code until a given condition is satisfied. A For loop is useful in such a case when we know how many times a block of code has to be executed. In VB.NET, the For loop is also known as For Next Loop.
Let's understand the For Next loop in detail.
Flowchart of For Next loop
The following flowchart represents the functioning of the For Next loop in the VB.NET programming language.
In the above flow chart, the first step is to initialize the variable name with the start value. And then, the value of the variable will be compared to the end expression or value. If the condition is true, the control enters the loop body and executes the statements. After that, the value of a variable will be automatically incremented by the compiler. Upon completion of each iteration, the current value of a variable will be again compared to the end expression. If the condition is not true, the controlled exit from the loop.
Example 1. Write a simple program to print the number from 1 to 10 using the For Next loop.
In the above example, we have initialized an integer variable i with an initial value 1. The For loop will continuously execute its body until the value of i is smaller or equal to 10. After each iteration, the value of i is automatically increased with 'Step 1'. If the value of i reached 10, the loop would be terminated and control transfer to the Main() function.
Further, we can change the Step in For Next loop. Write the following program to skip the number is 2.
As we can see in the above output, the value of the variable i is initialized with 1, and the value of i is skipped by 'Step 2' in the loop for each iteration to print the skipped number from 1 to 10.
Example 2: Write a simple program to print a table in the VB.NET.
Nested For Next Loop in VB.NET
In VB.NET, when we write one For loop inside the body of another For Next loop, it is called Nested For Next loop.
Following is the example of Nested For Next loop in VB.NET.
In the above example, at each iteration of the outer loop, the inner loop is repeatedly executed its entire cycles until the condition is not satisfied.
Example 2: Write a program to print a pattern in VB.NET.