Looping Construct in C#

Loop In C#

Loops execute one or more lines of code repetitively. The following loop constructs are supported by C#:

  • While Loop
  • Do-While Loop
  • For Loop
  • Interrupting Loops

The While Loop

The while loop construct executes a statement or block of statements for a definite number of times, depending on the condition.  The while statement always checks the condition before executing the statements in the loop.

When the execution reaches the last statement in the loop, control returns to the beginning of the loop. If the condition remains true then the statement within the loop is executed again. Execution of the statement continues until the condition in the loop evaluates to false.

As a simple example, consider the following code  for calculating the amount of money in a bank account after 10 years, assuming that interest is paid  each year and no other money flows into or out of the account.

Code

double balance=1000;
double interestRate=1.05;// 5%  interest /Year
balance*= interestRate;
balance*= interestRate;
balance*= interestRate;
balance*= interestRate;
balance*= interestRate;
balance*= interestRate;
balance*= interestRate;
balance*= interestRate;
balance*= interestRate;
balance*= interestRate;

Writing same code 10 times seems a bit wasteful, and what if you change the duration from 10 to 40 years?

You need to manually copy that code 40 times. So the same code can be replaced with the following code:

class Program

{

    static void Main(string[] args)

    {

        double balance, interestRate, targetBalance;

        Console.WriteLine("What is your current balance?");

        balance = Convert.ToDouble(Console.ReadLine());

        Console.WriteLine("What is your current annual interest rate (in %)?");

        interestRate = 1 + Convert.ToDouble(Console.ReadLine()) / 100.0;

        Console.WriteLine("What balance would you like to have?");

        targetBalance = Convert.ToDouble(Console.ReadLine());

 

        int totalYears = 0;

        while (balance < targetBalance)

        {

            balance *= interestRate;

            ++totalYears;

        }

        Console.WriteLine("In {0} year{1} you'll have a balance of {2}.",

                          totalYears, totalYears == 1 ? "" : "s", balance);

        Console.ReadKey();

    }

}

Execute the code and enter some values:

While-Loop-in-Csharp.jpg

In the preceding code we have created a double variable balance, interestRate, and targetBalance.

 

double balance, interestRate, targetBalance;

Console.WriteLine("What is your current balance?");

balance = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("What is your current annual interest rate (in %)?");

interestRate = 1 + Convert.ToDouble(Console.ReadLine()) / 100.0;

Console.WriteLine("What balance would you like to have?");

targetBalance = Convert.ToDouble(Console.ReadLine());

           
Using the code above we are just accepting a value for the variable balance, interestRate and targetBalance.           

int totalYears = 0;

while (balance < targetBalance)

{

   balance *= interestRate;

   ++totalYears;

}


This code simply repeats the simple annual calculation of the balance with a fixed interest rate as many time as necessary for the balance to satisfy the terminating condition. We are maintaining a count of how many years has been accounted for by incrementing the totalyears as a counter variable with each loop of the cycle.

Do-While Loop

The Do-While loop is similar to the While Loop. Both iterate until the specified condition becomes false.

However, in the Do-While loop, the body of the loop is executed at least once and the condition is evaluated for subsequent iteration. And the reason behind that is, the Boolean test in the While loop is done at the start of the loop, not at the end. But in the While-Loop the Boolean test in the while loop is done at the end of the loop.

The difference between the While and Do-While loop is shown in the following figure.

Do-While-Loop-flowchart-in-Csharp.jpg

Code

class Program

{

    static void Main(string[] args)

    {

        double balance, interestRate, targetBalance;

        Console.WriteLine("What is your current balance?");

        balance = Convert.ToDouble(Console.ReadLine());

        Console.WriteLine("What is your current annual interest rate (in %)?");

        interestRate = 1 + Convert.ToDouble(Console.ReadLine()) / 100.0;

        Console.WriteLine("What balance would you like to have?");

        targetBalance = Convert.ToDouble(Console.ReadLine());

        int totalYears = 0;

        do

        {

            balance *= interestRate;

            ++totalYears;

        }

        while (balance < targetBalance);

        Console.WriteLine("In {0} year{1} you'll have a balance of {2}.",

                         totalYears, totalYears == 1 ? "" : "s", balance);

        Console.ReadKey();

    }

}

Execute the code again but this time we are evaluating the target balance at the bottom.

Do-While-Loop--in-Csharp.jpg

The For Loop

The For loop executes the statement or block of statements for a specific number of times. To define a for loop you need the following information.

  • A starting value to initialize the counter variable
  • A condition for continuing the loop, involving the counter variable
  • An operation to be performed on the counter variable at the end of each loop cycle

The following code is the syntax of the For loop construct.

For (initialization; Test Expression; Increment/Decrement)
{
Statements.
}

Initialization: The initialization expression initializes the For loop construct. It is executed once at the beginning of the For loop.

Test Expression: The test expression determines when to terminate the loop execution. When the expression is evaluated to false, the loop terminates.

Increment/Decrement: The increment/decrement component gets invoked after each iteration.

All these components are optional.

You can create an infinite loop by omitting all the three expressions as in the following:

For (  ;    ;  )
{
. .  .
}

Let's see an example of a For loop. In this example we will print a table of 12 items on the console.

class Program

{

    static void Main(string[] args)

    {

        Console.WriteLine("Printing table of 12 on console.");

        for (int x = 1; x <= 10; x++)

        {

            Console.WriteLine("12 * " + x + " :" + x * 12);

        }

        Console.ReadLine();

    }

}


The output of the preceding code is as follows.

For-Loop-in-Csharp.jpg

Interrupting Loops

You can interrupt the loop in C# by applying some commands.

1. Break: The Break command simply exits the loop, and execution continues at the first line of code after the loop as shown in the following example

static void Main(string[] args)

{

    int i = 1;

    while (i <= 10)

    {

        if (i == 6)

            break;

        Console.WriteLine("{0}", i++);

    }

    Console.ReadLine();

}

This code writes out the numbers from 1 to 5 because the break command causes the loop to exit when i reaches 6.

Interrupting-Loop-in-Csharp.jpg

2. Continue: continue only stops the current cycle, not the entire loop, as shown here.           

int i;
for (i = 1; i <= 10; i++)
{
   if
((i % 2 == 0))
       continue;
   Console.WriteLine(i);
}
  
In the preceding example, whenever the reminder of i divided by 2 is zero, the continue statement stops the execution of the current cycle, so the output will be:

Continue-Loop-in-Csharp.jpg

3. Goto: The third method of interrupting the loop is to use a goto statement as in the following:
 

int i = 1;

while (i <= 10)

{

   if (i == 6)

   goto exitPoint;

   Console.WriteLine("{0}", i++);

}

exitPoint:

Console.WriteLine("this loop is interrupted using goto");

Console.ReadLine();
 
This code writes out the numbers from 1 to 5 because the goto command causes the loop to exit when i reaches 6.

Output

Goto-Loop-in-Csharp.jpg

Summary

Looping allows you to execute a block of code a number of times depending on the conditions you specify. You can use do and while loops to execute code while a Boolean expression evaluates to true, and a for loop to include the counter in your loop. The loop can be interrupted by continue, break or with the goto statements.