Fundamentals of Counting in Looping

Introduction

A loop is a statement that keeps checking a condition as being true and keeps executing a statement until the condition becomes false. In other words, a loop consists of performing a repeating action. The following three requirements should (must) be met. You must indicate:

  • When and how the loop will start
  • Under what condition the loop will change from one state or step to the other or to the next
  • What condition will make the loop stop
Fundamentals of Counting in Looping

Practical LearningPractical Learning: Introducing Counting and Looping

  1. Start Microsoft Visual Studio
  2. Create a new Console App named CountingAndLooping.
  3. If you want, in the Program.cs document, you can test the code pieces in this lesson

while a Condition is True

One of the techniques used to use a loop is to first perform an operation, then check a condition to repeat a statement. To support this, the C-based languages, including C#, provide an operator named while. The formula to use it is:

while(condition) statement;

Most of the time, the statement goes along with a way to move forward or backward. As a result, the section that has the statement is usually delimited by curly brackets that show the body of the while condition. The formula for the while condition becomes:

while(condition)
{
    . . .
    statement
    . . .
};

To perform a while loop, the compiler first examines the condition. If the condition is true, then it executes the statement. After executing the statement, the condition is checked again. As long as the condition is true, the compiler will keep executing the statement. When or once the condition becomes false, the compiler exits the loop.

The while loop can be illustrated as follows:

While

Most of the time, before entering in a while loop, you should have an object or a variable that has been initialized or the variable provides a starting value. From there, you can ask the compiler to check another condition and keep doing something as long as that condition is true. Here is an example:

// Consider a starting value as 0
int number = 1;

// As long as the above value is lower than 5, ...
while(number <= 5)
{
    // ... display that number
    Console.WriteLine("Make sure you review your time sheet before submitting it.");
           
    // Increase the number (or counter)
    number++;
    // Check the number (or counter) again. Is it still less than 5?
}

This would produce:

Make sure you review the time sheet before submitting it.
Make sure you review the time sheet before submitting it.
Make sure you review the time sheet before submitting it.
Make sure you review the time sheet before submitting it.
Make sure you review the time sheet before submitting it.
Press any key to continue . . .

The while loop is used to first check a condition and then execute a statement. If the condition is false, the statement would never execute. Consider the following code:

int number = 5;
   
while(number <= 4)
{
    Console.WriteLine("Make sure you review the time sheet before submitting it.");
           
    number++;
}

When this code executes, nothing from the while loop would execute because, as the condition is checked in the beginning, it is false and the compiler would not get to the statement.

Doing Something While a Condition is True

Sometimes, before executing a repeating action, or before checking the condition for the first time, you may want to first execute a statement. In other words, you want to first execute a statement before checking its condition. To make this possible, the C-based languages, which includes C#, use a combination of the do and the while keywords. The formula to follow is:

do statement while (condition);

To make your code easy to read, especially if the condition is long, you can (and should) write the while condition section on its own line. The formula would become:

do statement
    while (condition);

If the statement involves more than one line of code, you must include the statement section in a body delimited by curly brackets. The formula becomes:

do {
statement
} while (condition);

The body delimited by curly brackets can be used even if there is only one statement to execute. To make your code easy to read, although not required, you should indent the statement section.

The do...while condition executes a statement first. After the first execution of the statement, the compiler examines the condition. If the condition is true, then it executes the statement again. It will keep executing the statement as long as the condition is true. Once the condition becomes false, the looping (the execution of the statement) will stop. This can be illustrated as follows:

do...while

If the statement is a short one, such as made of one line, you can write it after the do keyword. Like the if and the while statements, the condition being checked must be included between parentheses. The whole do...while statement must end with a semicolon. Here is an example:

int number = 0;
       
do {
    Console.WriteLine("Make sure you review the time sheet before submitting it.");
           
    number++;
} while (number <= 4);

Console.WriteLine("==========================================================");

This would produce:

Make sure you review the time sheet before submitting it.
Make sure you review the time sheet before submitting it.
Make sure you review the time sheet before submitting it.
Make sure you review the time sheet before submitting it.
Make sure you review the time sheet before submitting it.
==========================================================
Press any key to continue . . .

Counting for a Loop

Some operations require that you visit each item in a range, usually a range of numbers. To let you do this, the C-based languages, including C#, provide the for keyword. The primary formula to follow is:

for(start; end; frequency) statement;

If the whole code you want to write is short, you can write the whole code on one line as in the above formula.

The for loop is typically used to visit each number of a range. For this reason, it is divided in three parts. The first section specifies the starting point of the range. This start expression can be a variable assigned to the starting value. An example would be int count = 0;.

The second section sets the counting limit. This end expression is created as a Boolean expression that can be true or false. An example would be count < 5. This means that the counting would continue as long as the value of start is less than 5. When such a condition becomes false, the loop or counting would stop.

The last section determines how the counting should move from one value to another. If you want the loop to increment the value from start, you can apply the ++ operator to it. Here is an example:

for (int number = 1; number <= 5; number++)
    Console.WriteLine("The time sheet was checked and this payroll has been approved.");

Console.WriteLine("===============================================================");

This would produce:

The time sheet was checked and this payroll has been approved.
The time sheet was checked and this payroll has been approved.
The time sheet was checked and this payroll has been approved.
The time sheet was checked and this payroll has been approved.
The time sheet was checked and this payroll has been approved.
===============================================================
Press any key to continue . . .

As mentioned above, if the code of the for section and that of the statement is short, you can write the whole code on one line. If the statement is long or you need many lines of code, in fact even if the statement is for one line of code, you should include it in curly brackets. The formula to follow would be:

for(start; end; frequency)
{
    statement;
}

If the statement is made of more than one line of code, that you must include the statement section in curly brackets.

Reversing the Counting Direction

Instead of proceeding from a lower to a higher value in a loop, you can visit the values from the end of a list to the beginning. To do this, for the first part of the loop, set the last value as the starting point. For the second part of the loop, specify the possible ending point as the first value. For its Boolean expression, you usually set a condition that would work backwards. This is usually done using the > or the >= operator. The last section usually applies the -- operator to the variable of the loop. The formula to follow can be the following:

for(end; start; frequency) statement;

Controlling a Loop

Loops and Conditional Statement Nesting

You can create a conditional statement in the body of a loop. This is referred to as nesting. Here is an example:

byte number = 0;

while (number < 5)
{
    Console.WriteLine("Make sure you review the time sheet before submitting it.");

    if(number == 2)
        Console.WriteLine("This is the third warning about your time sheet.");

    number++;
}

Console.WriteLine("===============================================================");

This would produce:

Make sure you review the time sheet before submitting it.
Make sure you review the time sheet before submitting it.
Make sure you review the time sheet before submitting it.
This is the third warning about your time sheet.
Make sure you review the time sheet before submitting it.
Make sure you review the time sheet before submitting it.
===============================================================
Press any key to continue . . .

On the other hand, you can nest a loop in a conditional statement.

Breaking the Flow of a Loop

As mentioned in our introductions, a loop is supposed to navigate from a starting point to an ending value. Sometimes, for any reason, you want to stop that navigation before the end of the loop. To support this, the C-based languages, which include C#, provide the break keyword. The formula to use the break statement is:

break;

Although made of only one word, the break statement is a complete statement; therefore, it can (and should always) stay on its own line (this makes the program easy to read).

The break statement applies to the most previous conditional statement to it; provided that previous statement is applicable. The break statement can be used in a while condition, in a do...while, or a for loops to stop an ongoing operation. Here is an example that is used to count the levels of a house from 1 to 12 but it is asked to stop at 3:

for(ubyte number = 0; number <= 5; number++)
{
    Console.WriteLine("The time sheet was checked and this payroll has been approved.");

    if(number == 2)
        break;
}

Console.WriteLine("===============================================================");

This would produce:

The time sheet was checked and this payroll has been approved.
The time sheet was checked and this payroll has been approved.
The time sheet was checked and this payroll has been approved.
===============================================================
Press any key to continue . . .

Continuing a Conditional Statement

Instead of stopping the flow of a loop, you may want to skip one of the values. To support this, the C-based languages such as C# provide the continue keyword. The formula to use it is:

continue;

When processing a loop, if the statement finds a false value, you can use the continue statement inside of a while, a do...while, or a for conditional statements to ignore the subsequent statement or to jump from a false Boolean value to the subsequent valid value, unlike the break statement that would exit the loop. Like the break statement, the continue keyword applies to the most previous conditional statement and should stay on its own line. Here is an example that is supposed to count the levels of a house from 1 to 6:

string strNumbers = "";

for (int number = 0; number <= 5; number++)
{
    if(number == 3)
        continue;

    strNumbers += number.ToString() + " ";

    Console.WriteLine("The list of numbers is {0}", strNumbers);
}

Console.WriteLine("===========================================");

This would produce:

The list of numbers is 0
The list of numbers is 0 1
The list of numbers is 0 1 2
The list of numbers is 0 1 2 4
The list of numbers is 0 1 2 4 5
===========================================
Press any key to continue . . .

Notice that, when the compiler gets to 3, it ignores it.

Changing a Value in the Loop

Inside a loop, you may want to put a flag that would monitor the evolution of a piece of code so that, if a certain value is encountered, instead of skipping the looping by 1, you can make it jump to a valued range of your choice. To do this, in the loop, check the current value and if it gets to one you are looking for, change it. Here is an example where a loop is asked to count from 0 to 15:

string strNumbers = "";

for (int number = 0; number < 15; number++)
{
    if (number == 6)
        number = 10;

    strNumbers += number.ToString() + " ";
}

Console.WriteLine("The list of numbers is {0}", strNumbers);
Console.WriteLine("===========================================");

This would produce:

The list of numbers is 0 1 2 3 4 5 10 11 12 13 14
===================================================
Press any key to continue . . .

Notice that, when the loop reaches 6, it is asked to jump to number 10 instead.

while(true)

For the different situations in which we used a while condition so far, we included a means of checking the condition. As an option, you can include just the true Boolean regular value in the parentheses of true. This would be done as follows:

while(true) statement;

If you have only one statement, you can write that statement on its own line. This would be done as follows:

while(true)
    statement;

Still in both cases, you can include the statement in curly brackets. If you have more than one statement, you must include them in curly brackets. This would be done as follows:

while(true) { statement};

while(true) {
    statement; }

If you are using Microsoft Visual Studio, to create a while loop, right-click the section where you want to add it and click Insert Snippet... Double-click Visual C#. In the list, double-click while:

While a Condition is True

The result is:

while(true)
{

}

For the different situations in which we used a while condition so far, we included a means of checking the condition. As an option, you can include juste the true Boolean regular value in the parentheses of true. Here is an example:

using static System.Console;

while (true)
    WriteLine("Application development is fun!!!");

This type of statement is legal and would work fine, but it has no way to stop because it is telling the compiler "As long as 'this' is true, ...". The question is, what is "this"? As a result, the program would run forever. Therefore, if you create a while(true) condition, in the body of the statement, you should (must) provide a way for the compiler to stop, that is, a way for the condition to be (or to become) false. This can be done by including an if condition. Here is an example:

ubyte i = 0;

while(true)
{
    if (i > 8)
        break;

    Console.WriteLine("Application development is fun!!!");

    i++;
}

Console.WriteLine("===============================");

This would produce:

Application development is fun!!!
Application development is fun!!!
Application development is fun!!!
Application development is fun!!!
Application development is fun!!!
Application development is fun!!!
Application development is fun!!!
Application development is fun!!!
Application development is fun!!!
===============================
Press any key to continue . . .

Instead of using while(true), you can first declare and initialize a Boolean variable, or you can use a Boolean variable whose value is already known. The value can come from a method or by other means.

Options for a Loop

A Variable for a Counter

To make the code of a for loop easy to read, you can put each part of the for expression on its own line. Here is an example:

for(int number = 0;
    number <= 4;
    number++)
    Console.WriteLine("The time sheet was checked and this payroll has been approved.");

Console.WriteLine("===============================================================");

In the above example, we declared the variable in the for expression. You can use a variable from any source or declare a variable before the loop. Here is an example:

// A variable for a loop
int number;

// Using a "for" loop       
for (number = 0; number <= 5; number++)
    Console.WriteLine("The time sheet was checked and this payroll has been approved.");

Console.WriteLine("===============================================================");

Omitting the Starting Point

In the above code, we first declared a variable, and then initialized it in the loop. If you have a variable that has been initialized and want to use it in the loop, in the section of the loop where the variable is supposed to be initialized, leave that section empty but include its semicolon. Here is an example:

int number = 0;
       
for(; number <= 5; number++)
            Console.WriteLine("The time sheet was checked and this payroll has been approved.");

Console.WriteLine("===============================================================");

for a while Loop

Here is an example of code we used earlier for a while loop:

using static System.Console;

int counter = 0;

while (counter <= 4)
{
    WriteLine("Make sure you review your time sheet before submitting it.");

    counter++;
}

We have already seen that you can declare and initialize a variable for a for loop, in which case you would omit the starting point of the loop. You can also omit the third part of the loop. In this case, in the body of the for loop, write a statement that specifies the next step of the loop. Here is an example:

using static System.Console;

int counter = 0;

for(; counter <= 4;)
{
    WriteLine("Make sure you review your time sheet before submitting it.");

    counter++;
}

Omitting the Parts for a Loop

The three sections of a for loop are required, but their contents are not. We have already seen how to omit the first and the third part of that loop. Well, you can also omit the second part. This means that you can define a for loop with all three empty parts:

for(; ; )
{
    WriteLine("Make sure you review your time sheet before submitting it.");
}

This code doesn't have any error and would compile just fine, except that it would run forever, until the computer crashes, is shut down, or runs out of memory. Therefore, the requirements of a for loop remain: the compiler needs to know how to start counting, how to get to the next step, and under what condition to stop the loop. Since the for loop can be created with all three empty sections, this means that you can (should/must) create those sections outside the loop. We have already seen how to create the first and the third sections outside of for(;...;). In the same way, you can create the second section outside of for(;...;). The problem is that you must let the compiler know what it should do when that section executes. The classic or simpler way is to create a conditional statement in the body of the loop and, in that statement, add a break line. This can be done as follows:

using static System.Console;

int counter = 0;

for(;;)
{
    WriteLine("Make sure you review your time sheet before submitting it.");

    counter++;
    
    if (counter > 4)
        break;
}

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2026, FunctionX Friday 16 October 2025, 13:36 Next