C# Loops

C# provides four different loops (for, while, do-while and foreachthat allow us to execute a block of code repeatedly until a certain condition is met. The for, while and do-while loops are essentially identical to those encountered in C++.
  • The for Loop

C# for loops provide a mechanism for iterating through a loop where we test whether a particular condition holds before we perform another iteration. The syntax is:

for (initializer; condition; iterator)
statement(s)

Example:

namespace Loops
{
    class Program
    {
        static void Main(string[] args)
        {
            int i;
            int mValue = 5;
            for (i = 1; i <= mValue; i++)
            {
                Console.WriteLine("\n"+i);
            }
            Console.ReadLine();
        }
    }
}   

C# Loops
                   
  
  • The while Loop

The while loop is identical to the while loop in C++ and Java. The while loop simply executes a block of code as long as the condition you give it is true.

The syntax is:

while(condition)
statement(s);

Example:

namespace Loops
{
    class Program
    {
        static void Main(string[] args)
        {
            int mValue = 1;

            while (mValue <= 5)
            {
                Console.WriteLine(mValue);
                mValue = mValue + 1;
            }
            Console.ReadLine();
        }
          
    }
}



























  • The do-while Loop

The do-while loop is the post-test version of the while loop. It does the same thing with the same syntax as do-while in C++ and Java. The opposite is true for the do loop, which works like the while loop in other aspects through. The do loop evaluates the condition after the loop has executed, which makes sure that the code block is always executed at least once. 

  • The foreach Loop

The foreach loop is the final C# looping mechanism that we will discuss.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Loops
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();
            list.Add("Richard Smith");
            list.Add("Rinor Haziri");          

            foreach (string Value in list)
                Console.WriteLine(Value);
            Console.ReadLine();
        }
          
    }
}



No comments:

Post a Comment