Monday, August 12, 2013

C# - While,For and Do While Loops

In c#,  we have few options that we can select when we need to create logical 'Loops' in our application, this article will review the available options, including practical examples. 

Loops, why do we need it? 

·         Loops are  useful when you need to repeat the     same operation.
·         Loops helps us to save time.
·         Loops makes our code much more readable.
·         Loops can save multiple code lines.

Example:

Let's assume that we need to print the number 0 – 10.

class Program
    {
        static void Main(string[] args)
        {
          Console.WriteLine("Without Loop:");
            Console.WriteLine("0");
            Console.WriteLine("1");
            Console.WriteLine("2");
            Console.WriteLine("3");
            Console.WriteLine("4");
            Console.WriteLine("5");
            Console.WriteLine("6");
            Console.WriteLine("7");
            Console.WriteLine("8");
            Console.WriteLine("9");
            Console.WriteLine("10");

            Console.WriteLine("----");

            Console.WriteLine("With Loop :");
            int num = 0;
            while (num <= 10)
            {
                Console.WriteLine(num);
                num++;
            }
           
        }
    }



As you can see, using a simple loop can save multiple code lines (just imagine if we need to print values for 0 till 1K…).

Available types Loops 

The Foreach Loop

The Foreach loop is a loop that created especially for arrays/Collections. Not like 'For' or 'While' loops, we don't need to create Indexer for the array length, in our case,using the Foreach loop will guaranty that we cover every member in the array.

Example:

//Creating the Array
char[] ArrayExample = new char[] { 'a', 'b', 'c', 'd' };

//Creating the Collection
Collection<int> CollectionExample = new Collection<int>() { 1, 2, 3, 4 };

//Example 1: Using Foreach loop to print information from an Array
foreach (char item in ArrayExample)
{
Console.WriteLine(item);
}

Console.WriteLine("----------------------");

//Example 2: Using Foreach loop to print information from a collection
foreach (var item in CollectionExample)
{
Console.WriteLine(item);
}





The For Loop

Not like the 'Foreach' loop, in the  'For' loop we need to define few variables before ewe can run it (Variables, number of iterations, Indexer...).

Example:

class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine(i);
            }
        }
    }

Result: 
















Now let's examine the syntax for this loop:

For (int i = 0; i <= 10; i++)
{
Console.WriteLine (i);
}

Int i = 0:

In this section we initialize a new variable (on first run the value set to '0'), that used to calculate the loop iterations before Breaking the operation.

I<=10

This section will affect the iterations number for this loop, in our case the loop will end when 'I' reach until 11(this condition will be checked before a new iteration is committed).

I++

This section responsible to update the iteration number, not like the condition that checked before running the next iteration, this section executed after each iteration.

Summary:

For (part 1: initialization of a variable, Part 2: Condition, Part 3: Condition Update)
Part 1: take place before the first run, will be configured single time.
Part 2: take place before iterations
Part 3: take place after code finished in {Code}.

The While Loop

That's the most basic loop available in every code language; this loop operates based on a simple condition at the start (I already showed an example at the start of the article) of the loop.

Example:
While (Condition)
{
Code
}

From this example you can easily understand that this loop will commit till the condition become 'TRUE'.

Do-While Loop

This loop Is almost a replica for the 'While' loop , the main difference is that in this loop we can be sure that we run the code at least one time before breaking the loop.

Simple diagram to demonstrate:
Loop Type
Conditions
Body
While
Checked Before running the loop
Executed after we validate the loop condition
Do While
Checked after the code executed
Executed before validating the loop condition

Example: 

























Result: 












working with Nested loops 

Nested loop is a simple and logical structure of two (or more) loops combining together, the nested loops structure will end only when the outer loop will close all iterations.

This logical structure will run with the following specification:
The Outer loop run for the first iteration ->
The inner loop triggered - >
After the inner loop completed ->
Outer loop will start a new iteration- >
Inner loop triggered again.

Why using it?
First, in some cases you simply must use it to resolve a complicated issues,
Second, using this structure you can cover a large amount of data and save multiple code lines in an efficient way.

Example:
Think about a folder structure with the following specification:
1000 folders, each folder should have 1M files.

Solution:
All we need is 2 loops:
Outer: Creating all folders
Inner: Creating all files per folder

An Additional classic example, is the “multiplication table” 

Using the ‘For’ loop:

class Program
    {
        static  void Main(string[] args)
        {
            for (int i = 1; i <= 10; i++) //Inner Loop
            {
                for (int b = 1; b <= 10; b++) //Outer Loop
                {                
                    Console.Write(i * b + " ");
                }
                Console.WriteLine();
            }
        }
    }

Using the ‘While’ loop :

static  void Main(string[] args)
        {
            int x = 1;
            while (x <= 10)
            {
                int y = 1;
                while (y <= 10)
                {
                    Console.Write("{0,2}", x * y);
                    y++;
                }
                Console.WriteLine();
                x++;
            }
        }


Result : 




No comments:

Post a Comment

My Presentations