Loops in Visual Basic

nested loop
A nested loop is a loop inside a loop. The loops do not have to be the same type. There can be a For loop inside a While loop; a For loop inside a For loop, etc. The inner loop is executed in its entirety for each execution of the outer loop.

Nested Loop Program

The illustration shows a design created using nested loops. The outer loop generates values for Num from 1 to 10.. The inner loop generates values for P from 2 to 4 and displays Math.Pow(Num,P) All of the values for one row are concatenated and displayed at the end of the inner loop. The statement to generate Num (in the outer loop) is executed 10 times, but the statement to compute power (in the inner loop) is executed 30 times!

'Programmer: Janet Joy
'Nested loops
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim Num, P As Integer
        Dim S As String
        For Num = 1 To 10
            S = "" & Num & " : "
            For P = 2 To 4
                S = S & Math.Pow(Num, P) & " "
    End Sub
End Class
Challenge: Format this so that it makes a nice neat table!

NEXT: For Each Loops