How do I use for loop statement?

Category: Introduction, viewed: 150 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:

*
**
***
****
*****
******
*******
********
*********
**********
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Network Sites

Statistics

Locations of visitors to this page