Zebra0.com

csharp loops

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

.nested loop
The outer loop generates values for num from 1 to 10..
The inner loop generates values for p from 2 to 4 and finds the value of 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 void Form1_Load(object sender, EventArgs e)
{
  // Put the numbers from 1 to 10 in a list box followed by 3 powers. 
  string s;
  for(int num=1; num<=10;num++)
  {
    s = "" + num + " :  ";
    for (int p=2;p<=4;p++)
    {
      s += Math.Pow(num, p) + " ";
    }
    listBox1.Items.Add(s);
 }
 }

End of lesson, Next lesson: