Loop In C# Programming With An Example

03:25
In previous article we have seen brief description of conditional statements which are back bone of programming. Here today we will see loop in C# programming and will see it with example. Speaking in layman term loops are used for task that need to perform representatively unless certain condition remains true and stop when that condition becomes false.


In programming languages loops are also important as conditional statements. Let me explain this with an simple example. If I will tell you to write program for printing 1 to 100 without loop statement. It will be very tedious task. Like this there are very different real-time task that need to be performed at that time loops becomes too handy for that.

C# provide following loops to handle different looping requirement:

While Loop: 

While loop is very simple of all. It simply execute the statement until condition becomes false.

Following is Syntax for the same:

while(condition expression)
{
//Statement
}

Let's take very simple example of writing tables of 5. Here the code for the same:

using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        { int a=5, b=1,c;//declaration and assignment of variables
            Console.WriteLine("Table Of 5 :");
            while (b<=10)//condition expression
            {
                //statements
                c = a * b;
                Console.WriteLine(a+" X "+b+" = "+c);
                b++;
            }
        }
    }
}
Output of the following code will be:
Table Of 5 :
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
Press any key to continue . . .
In above program there are three variables viz a,b and c. Value of variable a is constant "a=5". On the other hand value of b keeps on changing till 10. Both values held by a and b are multiplied and their output is then stored in variable c. We can write a single program in all loop but every loop have their own purpose. Now we will see 

Do........While Loop:

Do while loop is similar to while loop. There is only one difference between while and do..while loop. In While loop there is always first condition is checked and then it entered in to loop. 

Syntax of Do.....While Loop:

do{
//statement
}while(condition expression);
Here notice we end/terminate the do..while loop after while condition.
using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 5;
           do
            {
                Console.WriteLine("This statement will execute only in do...while loop............");
            } while (a > 10) ;
        }
    }
}
On the other hand Do.. While loop one time statement is executed and then condition is checked. I am sure you are confused. So we will take on example:

I will write both program but both will have wrong false value at the first iteration itself.

Example of While Loop:
using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 5;
            while (a>10)
            {
                Console.WriteLine("This statement will not execute............");
            }
        }
    }
}
This program will execute without any error but you will not get anything as output.

Example of Do While Loop:
using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 5;
           do
            {
           Console.WriteLine("This statement will execute only in do...while loop............");            } while (a > 10) ;
        }
    }
}

Output:
This statement will execute only in do...while loop............ 
Here even if the condition is false then too the statement in the body of the loop get executed once. Now let's take same example for this loop is as follows:

using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 5,b=1,c;
           do
            {
                c = a * b;
                Console.WriteLine(a + " X " + b + " = " + c);
                b++;
            } while (b <= 10) ;
        }
    }
}

Output:
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
Press any key to continue . . .
For Loop:

This loop is most preferred loop in programming and most easy to write. Let's first see the syntax of the For loop:

Syntax:

for(initialization, condition, increment)
{
//Statement(s);
}
For loop is divided into 3 parts viz. Initialization, Condition, Increment:

for (int b = 1; b <= 10; b++)
  • Initialization:
    When for loop get executed, it first enter into initialization part and it only executed once. This step allow you to declare variable that have only scope in that for loop. In above example when loop started execution then it will first check int b=1; Here we initialize b and assign the value to it. Here semicolon indicate end of initialization phase termination or end of initialization phase
  • Condition:
    In next step it evaluate conditional expression. After the first iteration only Condition and increment phase of loop is checked. Initialization is ignored. In condition evaluated to be true then loop body get executed, or else it will be skipped and control jumps to the net statement. In above example we are checking for value of variable b if it less then or equal to 10 then only it will execute loop body or else it will skip loop and transfer control to next statement.
  • Increment:
    In this phase after checking for condition you can increment or decrement value of variable. Here we are incrementing value of variable b by 1. 
So this way loop iterated though itself until condition becomes false. Let's take that example of table of 5 using for loop:

using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 5,c;
            for (int b = 1; b <= 10; b++)
            {
                c = a * b;
                Console.WriteLine(a + " X " + b + " = " + c);
            }
        }
    }
}
Output:
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50

So here all are loop provided in C# is explained with example. One foreach loop is remaining but we will see that in detail at later sessions. But when we talk about Loop we need to know some 

Loop Control Statement:

Loop control statements are used for changing th normal execution of the programming sequences of loop. There are two control statement provided by C# as follows:

break statement:

Break statement is used as for throwing control out of the loop. When compiler encounters beak keyword it will transfer control out of loop. Let's take the example we will initialize one variable with value of 1 and we will increment value by 1 each time we will terminate the loop once value of variable is 5 using break statement.
using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 1;
            while (a<10)
            {
                Console.WriteLine("Value of A is "+a);
                a++;
                if (a>5)
                {
                    break;
                }
            }
            Console.WriteLine("This will execute once break statement terminate the loop.....");
        }
    }
}
Output:
Value of A is 1
Value of A is 2
Value of A is 3
Value of A is 4
Value of A is 5
This will execute once break statement terminate the loop.....
continue statement:
 This statement will skip the intimidate next statement then it will pass control back to condition expression. And then it will evaluate. In this example we will increment the value of variable by one and when value of that variable is 5 I don't want to print it. Other then that we will print all the values:

using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 1;
            while (a < 10)
            {
                if (a == 5)
                {
                    a++;
                    continue;
                }
                Console.WriteLine("Value of A is " + a);
                a++;
            }
        }
    }
}

Output:

Value of A is 1
Value of A is 2
Value of A is 3
Value of A is 4
Value of A is 6
Value of A is 7
Value of A is 8
Value of A is 9
Press any key to continue . . . 
Check on the output, value of variable 5 is not printed.  So when it enter in condition when we check a==5 after that it will increment value of a by 1 and then continue statement transfer control directly to loop statement.

Infinite Loop:
There are sometimes condition arises where by mistake we write code such a way that condition expression always remains true then loop will run forever. This kind of loop. For example:

using System;
using System.Collections.Generic;
namespace Type_of_loop
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 1;
            while (a==1)
            {
                Console.WriteLine("This is infinite loop......");
            }
        }
    }
}
When you execute above code, it will execute forever unless you do not stop it manually.

With this we are all gone through what is loops and what types of loop C# provide. We have also seen what are loop control statement and concept of infinite loop, all of this with an example. Do comment below if you find this article useful or have nay query thanks for reading.

Share this

Related Posts

Previous
Next Post »