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!

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.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) & " "
     Next
     lstNumbers.Items.Add(S)
  Next
End Sub
Challenge: Format this so that it makes a nice neat table!
INDEX, A Demo loop program, For Loops, Step: change the increment, While Loops, While, cont., Endless loops, Do Loops, Nested Loops, For Each Loops, Graphics with Loops
Next lesson: Arrays in Visual Basic

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Nested Loops