How do I use for loop statement?

Category: Introduction, viewed: 3K time(s).

The for loop executes a statement or a block of statement repeatedly until the expression specified in the loop statement equals to false. This loop is useful for iterating an array variable or doing a sequential processes.

using System;

namespace Kodecsharp.Example.Intro
{
    class ForDemo
    {
        public static void Main(string[] args)
        {
            //
            // create a for loop iterating from 0 and continue while
            // i is less that 10.
            //
            for (int i = 0; i < 10; i++)
            {
                //
                // a for loop for printing stars (asterisk) from 0 to
                // the length of i.
                //
                for (int j = 0; j <= i; j++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }

            Console.ReadLine();
        }
    }
}

The example above (we take the outer loop) can be explained as follow:

  • First, initialize the i variable with zero, this means our loop start from zero.
  • Second, the for loop check whether i has the value less than 10 and execute the block if it is true.
  • Third, increment the i variable. The loop will be reevaluated whether the condition still true. If it is false the control will go outside the loop.

 

The result of our loop above is:

*
**
***
****
*****
******
*******
********
*********
**********
Powered by Disqus