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:

Practical LearningPractical Learning: Introducing Looping

  1. Start Microsoft Visual Studio and create a new Console App (that support .NET 8.0 (Long-Term Support)) named StraightLineMethod1
  2. Change the Program.cs document as follows:
    using static System.Console;
    
    int estimatedLife = 0;
    double machineCost = 0.00;
    double salvageValue = 0.00;
    
    Title = "Depreciation: Straight-Line Method";
    WriteLine("Enter the values for the machine depreciation");
    
    try
    {
        Write("Machine Cost:              ");
        machineCost = double.Parse(ReadLine()!);
    }
    catch (FormatException fex)
    {
        WriteLine("You might have typed a valid value that represents the " +
                  "cost of the machine. Since you did not provide a " +
                  "valid value, we will set the machine cost to 0.00.");
        WriteLine("The machine error is: " + fex.Message);
    }
    catch(Exception ex)
    {
        WriteLine("The application caused an error as: " + ex.Message);
    }
    
    try
    {
        Write("Salvage Value:             ");
        salvageValue = double.Parse(ReadLine()!);
    }
    catch (FormatException fex)
    {
        WriteLine("You must have provided that value you estimate the machine  " +
                  "will have at the end of the cycle (or the end of its " +
                  "life). Since you didn't enter a valid value, we will " +
                  "consider the estimated end value to 0.00.");
        WriteLine("The machine error is: " + fex.Message);
    }
    catch (Exception ex)
    {
        WriteLine("The application caused an error as: " + ex.Message);
    }
    
    try
    {
        Write("Estimated Life (in Years): ");
        estimatedLife = int.Parse(ReadLine()!);
    }
    catch (FormatException fex)
    {
        WriteLine("You didn't enter a valid number of years for the life of " +
                  "the machine. Instead, we will consider that this machine " +
                  "has no life, or a life of 0 years.");
        WriteLine("The machine error is: " + fex.Message);
    }
    catch (DivideByZeroException dze)
    {
        WriteLine("The value for the length of the estimated life of the machine must always be greater than 0.");
        WriteLine("The machine error is: " + dze.Message);
    }
    catch (Exception ex)
    {
        WriteLine("The application caused an error as: " + ex.Message);
    }
    
    double depreciatiableAmount = machineCost          - salvageValue;
    double depreciationRate     = 100                  / estimatedLife;
    double yearlyDepreciation   = depreciatiableAmount / estimatedLife;
    
    Clear();
    
    WriteLine("====================================");
    WriteLine("Depreciation - Straight-Line Method");
    WriteLine("------------------------------------");
    WriteLine("Machine Cost:        {0}", machineCost);
    
    WriteLine("Salvage Value:       {0}", salvageValue);
    WriteLine("Estimate Life:       {0} Years", estimatedLife);
    WriteLine("Depreciation Rate:   {0}%", depreciationRate);
    WriteLine("------------------------------------");
    WriteLine("Depreciable Amount:  {0}", depreciatiableAmount);
    WriteLine("Yearly Depreciation: {0}", yearlyDepreciation);
    WriteLine("====================================");
  3. To execute and test the application, on the main menu, click Debug -> Start Without Debugging
  4. At the requests, type the following values and press Enter after typing each value:
    Machine Cost:   22580
    Salvage Cost:   3875
    Estimated Life: 5
  5. Press Enter:
    ====================================
    Depreciation - Straight-Line Method
    ------------------------------------
    Machine Cost:        22580
    Salvage Value:       3875
    Estimate Life:       5 Years
    Depreciation Rate:   20%
    ------------------------------------
    Depreciable Amount:  18705
    Yearly Depreciation: 3741
    ====================================
    
    Press any key to close this window . . .
  6. Return to your programming environment

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.

Introduction to Loops and Lists

As you may know already, a list is a group of items. Here is an example of a list of numbers with each number stored in a variable:

double number1 = 12.44;
double number2 = 525.38;
double number3 = 6.28;
double number4 = 2448.32;
double number5 = 632.04;

The items are grouped from a starting to an ending points. The list can be created as an array. Here is an example:

double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

The list has a number of items. We saw that you can specify the number of items when creating the array. Here is an example:

double[] numbers = new double[5] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

Or, to get the number of items of an array, the array variable is equipped with a property named Length that it gets from the Array class. Here is an example of accessing it:

using static System.Console;

double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
       
WriteLine("Number of Items in the array: {0}", numbers.Length);
WriteLine("=================================");

This would produce:

Number of Items in the array: 5
=================================
Press any key to continue . . .

Each item can be located by its index from 0 to number-of-items - 1. Here is an example that accesses each of the items:

double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

Console.WriteLine("Number: {0}", numbers[0]);
Console.WriteLine("Number: {0}", numbers[1]);
Console.WriteLine("Number: {0}", numbers[2]);
Console.WriteLine("Number: {0}", numbers[3]);
Console.WriteLine("Number: {0}", numbers[4]);
Console.WriteLine("============================");

This would produce:

Number: 12.44
Number: 525.38
Number: 6.28
Number: 2448.32
Number: 632.04
============================
Press any key to continue . . .

As opposed to accessing one item at a time, a loop allows you to access the items as a group. Each item can still be accessed by its index. You can first declare a variable that would hold the index for an item. Here is an example:

int counter = 0;
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

To access an item in a loop, use the name of the array but pass the index in the square brackets of the variable. Here is an example:

int counter = 0;
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

while (counter <= 4)
{
    Console.WriteLine("Number: {0}", numbers[counter]);
           
    counter++;
}

WriteLine("=================================");

In the same way, to change the value of an item, access it by its index and assign the desired value to it. Here is an example:

int counter = 0;
int[] numbers = new int[] { 203, 81, 7495, 40, 9580 };

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

while (counter <= 4)
{
    Console.WriteLine("Number: {0}", numbers[counter]);
           
    counter++;
}

Console.WriteLine("-------------------------------------");
Console.WriteLine("Updating the numbers of the list...");

counter = 0;
Random rndNumber = new Random();

while (counter <= 4)
{
    numbers[counter] = rndNumber.Next(1001, 9999);

    counter++;
}

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

counter = 0;

Console.WriteLine("Updated Numbers");

while (counter <= 4)
{
    Console.WriteLine("Number: {0}", numbers[counter]);

    counter++;
}

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

This would produce:

====================================
Original List
Number: 203
Number: 81
Number: 7495
Number: 40
Number: 9580
-------------------------------------
Updating the numbers of the list...
-------------------------------------
Updated Numbers
Number: 9822
Number: 6086
Number: 8411
Number: 5176
Number: 4202
====================================
Press any key to continue . . .

Practical LearningPractical Learning: Introducing Loops in Lists

  1. Change the document as follows:
    using static System.Console;
    
    int    estimatedLife = 0;
    double machineCost   = 0.00;
    double salvageValue  = 0.00;
    
    Title = "Depreciation: Straight-Line Method";
    WriteLine("Enter the values for the machine depreciation");
    
    try
    {
        Write("Machine Cost:              ");
        machineCost = double.Parse(ReadLine()!);
    }
    catch(Exception ex) when (ex is FormatException fex)
    {
        WriteLine("You might have typed a valid value that represents the " +
                  "cost of the machine. Since you did not provide a " +
                  "valid value, we will set the machine cost to 0.00.");
        WriteLine("The machine error is: " + fex.Message);
    }
    
    try
    {
        Write("Salvage Value:             ");
        salvageValue = double.Parse(ReadLine()!);
    }
    catch(Exception ex) when (ex is FormatException fex)
    {
        WriteLine("You must have provided that value you estimate the machine  " +
                  "will have at the end of the cycle (or the end of its " +
                  "life). Since you didn't enter a valid value, we will " +
                  "consider the estimated end value to 0.00.");
        WriteLine("The machine error is: " + fex.Message);
    }
    
    try
    {
        Write("Estimated Life (in Years): ");
        estimatedLife = int.Parse(ReadLine()!);
    }
    catch (Exception ex) when (ex is FormatException fex)
    {
        WriteLine("You didn't enter a valid number of years for the life of " +
                  "the machine. Instead, we will consider that this machine " +
                  "has no life, or a life of 0 years.");
        WriteLine("The machine error is: " + fex.Message);
    }
    catch (Exception ex) when (ex is DivideByZeroException dze)
    {
        WriteLine("The value for the length of the estimated life of the machine must always be greater than 0.");
        WriteLine("The machine error is: " + dze.Message);
    }
    
    double depreciatiableAmount = machineCost          - salvageValue;
    double depreciationRate     = 100                  / estimatedLife;
    double yearlyDepreciation   = depreciatiableAmount / estimatedLife;
    
    Clear();
    
    WriteLine("====================================");
    WriteLine("Depreciation - Straight-Line Method");
    WriteLine("------------------------------------");
    WriteLine("Machine Cost:        {0}", machineCost);
    
    WriteLine("Salvage Value:       {0}", salvageValue);
    WriteLine("Estimate Life:       {0} Years", estimatedLife);
    WriteLine("Depreciation Rate:   {0}%", depreciationRate);
    WriteLine("------------------------------------");
    WriteLine("Depreciable Amount:  {0}", depreciatiableAmount);
    WriteLine("Yearly Depreciation: {0}", yearlyDepreciation);
    WriteLine("====================================");
    
    int i = 1;
    int year = 1;
    double[] bookValues = new double[estimatedLife + 1];
    bookValues[0] = machineCost;
    
    while (i <= @estimatedLife - 1)
    {
        bookValues[i] = bookValues[i - 1] - yearlyDepreciation;
        i++;
    }
    
    i = 0;
    bookValues[estimatedLife] = salvageValue;
    
    WriteLine("                   Accumulated");
    WriteLine("Year  Book Value   Distribution");
    
    while (i <= estimatedLife - 1)
    {
        double accumulatedDepreciation = yearlyDepreciation * year;
    
        WriteLine("------------------------------------");
        WriteLine("  {0} {1, 10} {2, 12}", year, bookValues[i], accumulatedDepreciation);
    
        i++;
        year++;
    }
    
    WriteLine("====================================");
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging
  3. Enter the requested values as follows and press Enter after each value:
    Machine Cost:   7448.85
    Salvage Value:  955.50
    Estimated Life: 5
  4. Press Enter:
    ====================================
    Depreciation - Straight-Line Method
    ------------------------------------
    Machine Cost:        7448.85
    Salvage Value:       955.5
    Estimate Life:       5 Years
    Depreciation Rate:   20%
    ------------------------------------
    Depreciable Amount:  6493.35
    Yearly Depreciation: 1298.67
    ====================================
                       Accumulated
    Year  Book Value   Distribution
    ------------------------------------
      1    7448.85      1298.67
    ------------------------------------
      2    6150.18      2597.34
    ------------------------------------
      3    4851.51      3896.01
    ------------------------------------
      4    3552.84      5194.68
    ------------------------------------
      5    2254.17      6493.35
    ====================================
    Press any key to continue . . .
  5. Press Enter to close the window and return to your programming environment
  6. To start a new project, on the main menu of Microsoft Visual Studio, click File -> New -> Project... and create a new C# Console application (.NET 8.0 (Long-Term Support)) named DoubleDecliningBalance1
  7. In the Solution Explorer, right-click Program.cs and click Rename
  8. Type DepreciationEvaluation (to get DepreciationEvaluation.cs)
  9. Press Enter

Omitting a Looping Variable

Remember that when you don't need a variable to hold a value, you can directly use the value where it is needed. This is also valid for a list of values you are using in a loop. This means that, when performing a while operation that involves an array, if you will use a list only once, you can create that list directly where it is needed. Everything else remains the same. Consider an earlier code section as follows:

int counter = 0;
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

while (counter <= 4)
{
    Console.WriteLine("Number: {0}", numbers[counter]);

    counter++;
}

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

If you will use the array only once, you can create it directly where it is needed as follows:

int counter = 0;

while (counter <= 4)
{
    Console.WriteLine("Number: {0}", new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 }[counter]);

    counter++;
}

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

If you want, to make your code a little easier to read, you can write some of its sections on different lines. Here is an example:

int counter = 0;

while (counter <= 4)
{
    Console.WriteLine("Number: {0}",
                      new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 }[counter]);

    counter++;
}

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

You can also write the above code like this:

int counter = 0;

while (counter <= 4)
{
    Console.WriteLine("Number: {0}",
                      new double[]
                      {
                          12.44, 525.38, 6.28, 2448.32, 632.04
                      }[counter]);

    counter++;
}

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

Or like this:

int counter = 0;

while (counter <= 4)
{
    Console.WriteLine("Number: {0}",
                      new double[]
                      {
                          12.44,
                          525.38,
                          6.28,
                          2448.32,
                          632.04
                      }[counter]);

    counter++;
}

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

Or like this:

int counter = 0;

while (counter <= 4)
{
    Console.WriteLine("Number: {0}",
                      new double[]
                      {
                            12.44,
                           525.38,
                             6.28,
                          2448.32,
                           632.04
                      } [
                              counter
                        ]);

    counter++;
}

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

Doing Something While a Condition is True

Introduction

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 included inside 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 . . .

Doing Something on a List

We saw that a while loop first checks a condition before performing an action. A do...while first performs an action before checking a condition. That's their main difference. Otherwise, you can perform a do...while operation where you would have used a while loop. This is also valid for lists such as arrays. Consider a while loop we used earlier as follows:

int counter = 0;
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

while (counter <= 4)
{
    Console.WriteLine("Number: {0}", numbers[counter]);

    counter++;
}

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

Instead of first checking a condition before performing an action in a while loop, you may want to first perform the desired action before checking a condition. In that case, the above code can be changed as follows:

int counter = 0;
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

do
{
    Console.WriteLine("Number: {0}", numbers[counter]);

    counter++;
} while (counter <= 4);

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

Remember that the array variable may be necessary only if you are planning to use that variable more than once. Otherwise, you can create the array directly where it is used. This can be done as follows:

int counter = 0;

do
{
    Console.WriteLine("Number: {0}",
                      new double[]
                      {
                          12.44, 525.38, 6.28, 2448.32, 632.04
                      }[counter]);

    counter++;
} while (counter <= 4);

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

Practical LearningPractical Learning: doing Something while a Condition is True

  1. Change the document as follows:
    using static System.Math;
    using static System.Console;
    
    WriteLine("=-= Depreciation - Double Declining Balance =-=");
    WriteLine("-----------------------------------------------");
    WriteLine("Provide the following values about the machine");
    
    double machineCost   = 0d;
    int    estimatedLife = 0;
    
    try
    {
        Write("Machine Cost:   ");
        machineCost = double.Parse(ReadLine()!);
    }
    catch(FormatException fe)
    {
        WriteLine("Please provide a valid value for the cost of the machine. " +
                  "The error produced is: " + fe.Message);
    }
    
    try
    {
        Write("Estimated Life: ");
        estimatedLife = int.Parse(ReadLine()!);
    }
    catch(FormatException fe)
    {
        WriteLine("You must provide a valid number for " +
                  "the length of the life of the machine. " +
                  "The error produced is: " + fe.Message);
    }
    
    double decliningRate = (100.00 / estimatedLife) * 2.00;
    double depreciation = machineCost * decliningRate / 100.00;
    
    Clear();
    
    WriteLine("   =-=    Depreciation - Double Declining Balance    =-=");
    WriteLine("===========================================================");
    WriteLine("Depreciation Estimation");
    WriteLine("-----------------------------------------------------------");
    WriteLine("Machine Cost:               {0:N}", machineCost);
    WriteLine("-----------------------------------------------------------");
    WriteLine("Estimated Life:             {0} years", estimatedLife);
    WriteLine("-----------------------------------------------------------");
    WriteLine("Declining Rate:             {0:N}", decliningRate);
    WriteLine("-----------------------------------------------------------");
    WriteLine("Depreciation First Year:    {0:N}", depreciation);
    WriteLine("===========================================================");
    
    int i = 1;
    int year = 1;
    double[] yearlyDepreciations = new double[estimatedLife];
    double[] bookValuesEndOfYear = new double[estimatedLife];
    double[] bookValuesBeginningOfYear = new double[estimatedLife];
    
    // Year 1
    bookValuesBeginningOfYear[0] = machineCost;
    yearlyDepreciations[0] = machineCost * decliningRate / 100.00;
    bookValuesEndOfYear[0] = machineCost - yearlyDepreciations[0];
    
    // The other years
    do
    {
        yearlyDepreciations[i] = bookValuesEndOfYear[i - 1] * decliningRate / 100.00;
        bookValuesEndOfYear[i] = bookValuesEndOfYear[i - 1] - yearlyDepreciations[i];
        bookValuesBeginningOfYear[i] = bookValuesEndOfYear[i - 1];
        i++;
    } while (i <= estimatedLife - 1);
    
    i = 0;
    
    WriteLine("  Book Value at                              Book Value at");
    WriteLine("Beginning of Year   Depreciation for Year    End of Year");
    WriteLine("-----------------------------------------------------------");
    
    do
    {
        WriteLine("{0,10}{1,22}{2,20}", year,
                  Ceiling(@bookValuesBeginningOfYear[i]),
                  Ceiling(@yearlyDepreciations[i]),
                  Ceiling(@bookValuesEndOfYear[i]));
        WriteLine("-----------------------------------------------------------");
    
        i++;
        year++;
    } while (i <= estimatedLife - 1);
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging
  3. When requested, type the Machine Cost as 24,669.55 and press Enter
  4. Type the Estimated Life as 8 and press Enter:
       =-=    Depreciation - Double Declining Balance    =-=
    ===========================================================
    Depreciation Estimation
    -----------------------------------------------------------
    Machine Cost:               24,669.55
    -----------------------------------------------------------
    Estimated Life:             8 years
    -----------------------------------------------------------
    Declining Rate:             25.00
    -----------------------------------------------------------
    Depreciation First Year:    6,167.39
    ===========================================================
      Book Value at                              Book Value at
    Beginning of Year   Depreciation for Year    End of Year
    -----------------------------------------------------------
             1                 24670                6168
    -----------------------------------------------------------
             2                 18503                4626
    -----------------------------------------------------------
             3                 13877                3470
    -----------------------------------------------------------
             4                 10408                2602
    -----------------------------------------------------------
             5                  7806                1952
    -----------------------------------------------------------
             6                  5855                1464
    -----------------------------------------------------------
             7                  4391                1098
    -----------------------------------------------------------
             8                  3293                 824
    -----------------------------------------------------------
    
    Press any key to close this window . . .
  5. Start a new Console App (that support .NET 8.0 (Long-Term Support)) named SumYearsDigits1
  6. In the Solution Explorer, right-click Program.cs and click Rename
  7. Type SumYearsDigits (to get SumYearsDigits.cs)
  8. Press Enter

Counting for a Loop

Introduction

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.

For a List

The primary purpose of a loop is to act on a list, such as an array of items, a list of numbers, etc. As it happens, mathematics (or algebra) automatically provides a list of numbers. This makes it possible to automatically have available a list of numbers as soon as you create an array. On the other hand, if you want a particular list of numbers, you can explicitly create it, as we saw with the while loop. After creating such an array, you can use a for loop to access each item by its position. The formula you can use is:

// Create a list or array of objects

for(int counter; counter[<][<=][>][>=] start-or-end-value; counter-frequency)
{
    // Optional operations
    list-or-array-of-objects[counter];
    // Optional operations
}

Based on this, a for loop primary performs the same operations as a while or a do...while loop. The primary difference is that, for a while or a do...while loop, you can (must) first declare, outside the loop, a variable that holds the starting value of the loop. For a for loop, you can also first declare a variable for the starting value, which you can do outside the loop, but, by tradition, that variable is declared in the parentheses of the for loop. Other than in the body of any of those loops, you can access the elements of the array or list using square brackets. Consider a while loop we used earlier as follows:

int counter = 0;
// Optional things here
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

while (counter <= 4)
{
    Console.WriteLine("Number: {0}", numbers[counter]);

    counter++;
}

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

Using a for loop, the above code can be changed as follows:

double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

for(int counter = 0;counter <= 4; counter++)
{
    Console.WriteLine("Number: {0}", numbers[counter]);
}

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

As stated already, an array variable is necessary only if you are planning to use the list many times. Otherwise, you can create the array directly where you need it. Here is an example:

for(int counter = 0;counter <= 4; counter++)
{
    Console.WriteLine("Number: {0}", new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 }[counter]);
}

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

Practical LearningPractical Learning: Counting for a Loop

  1. Change the document as follows:
    using static System.Math;
    using static System.Console;
    
    double GetMachineCost()
    {
        double machineCost = 0d;
    
        WriteLine("=-= Depreciation - Sum-of-the-Year's Digits =-=");
        WriteLine("----------------------------------------------");
    
        try
        {
            WriteLine("Provide the following values about the machine");
            Write("Machine Cost:   ");
            machineCost = double.Parse(ReadLine()!);
        }
        catch (FormatException fe)
        {
            WriteLine("The value you provided for the machine cost cannot be used.");
            WriteLine("The error reported is: " + fe.Message);
        }
    
        return machineCost;
    }
    
    double GetSalvageValue()
    {
        double salvageValue = 0d;
    
        try
        {
            Write("Salvage Value:  ");
            salvageValue = double.Parse(ReadLine()!);
        }
        catch (FormatException fe)
        {
            WriteLine("The value you provided for the machine cost cannot be used.");
            WriteLine("The error reported is: " + fe.Message);
        }
    
        return salvageValue;
    }
    
    int GetEstimatedLife()
    {
        int estimatedLife = 0;
    
        try
        {
            Write("Estimated Life: ");
            estimatedLife = int.Parse(ReadLine()!);
        }
        catch (FormatException fe)
        {
            WriteLine("The value you provided for the machine cost cannot be used.");
            WriteLine("The error reported is: " + fe.Message);
        }
    
        return estimatedLife;
    }
    
    double cost = GetMachineCost();
    double salvage = GetSalvageValue();
    int life = GetEstimatedLife();
    
    double depreciatiableAmount = cost - salvage;
    
    Clear();
    
    WriteLine("=-= Depreciation - Sum-of-the-Year's Digits =-=");
    WriteLine("===============================================");
    WriteLine("Depreciation Estimation");
    WriteLine("-----------------------------------------------");
    WriteLine("Machine Cost:             {0:N}", cost);
    WriteLine("Salvage Value:            {0:N}", salvage);
    WriteLine("Estimated Life:           {0}", life);
    WriteLine("depreciatiable Amount:    {0:N}", depreciatiableAmount);
    
    int year = 1;
    int counter = 0;
    int sumOfYears = (life * (life + 1)) / 2;
    double[] depreciations = new double[life];
    string[] fractions = new string[life];
    
    for (int i = 0; i <= life - 1; i++)
    {
        fractions[counter] = (i + 1) + "/" + sumOfYears;
        depreciations[counter] = (depreciatiableAmount * (i + 1)) / sumOfYears;
        counter++;
    }
    
    WriteLine("===============================================");
    WriteLine("Year        Fraction        Depreciation");
    WriteLine("-----------------------------------------------");
    
    for (int i = 0; i <= life - 1; i++)
    {
        WriteLine("{0,3}{1,15}{2,20}", year, fractions[i], Ceiling(@depreciations[i]));
        WriteLine("-----------------------------------------------");
    
        year++;
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging
  3. When requested, type the Machine Cost as 6,849.95 and press Enter
  4. Type the Salvage Value as 524.85 and press Enter
  5. Type the Estimated Life as 5 and press Enter:
    =-= Depreciation - Sum-of-the-Year's Digits =-=
    ===============================================
    Depreciation Estimation
    -----------------------------------------------
    Machine Cost:             6,849.95
    Salvage Value:            524.85
    Estimated Life:           5
    depreciatiable Amount:    6,325.10
    ===============================================
    Year        Fraction        Depreciation
    -----------------------------------------------
      1           1/15                 422
    -----------------------------------------------
      2           2/15                 844
    -----------------------------------------------
      3           3/15                1266
    -----------------------------------------------
      4           4/15                1687
    -----------------------------------------------
      5           5/15                2109
    -----------------------------------------------
    
    Press any key to close this window . . .
  6. Return to your programming environment

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;

Practical LearningPractical Learning: Reversing the Counting Direction

  1. Change the counting as follows:
    using static System.Math;
    using static System.Console;
    
    double GetMachineCost()
    {
        double machineCost = 0d;
    
        WriteLine("=-= Depreciation - Sum-of-the-Year's Digits =-=");
        WriteLine("----------------------------------------------");
    
        try
        {
            WriteLine("Provide the following values about the machine");
            Write("Machine Cost:   ");
            machineCost = double.Parse(ReadLine()!);
        }
        catch(Exception exc) when (exc is FormatException fe)
        {
            WriteLine("The value you provided for the machine cost cannot be used.");
            WriteLine("The error reported is: " + fe.Message);
        }
    
        return machineCost;
    }
    
    double GetSalvageValue()
    {
        double salvageValue = 0d;
    
        try
        {
            Write("Salvage Value:  ");
            salvageValue = double.Parse(ReadLine()!);
        }
        catch (Exception exc) when (exc is FormatException fe)
        {
            WriteLine("The value you provided for the machine cost cannot be used.");
            WriteLine("The error reported is: " + fe.Message);
        }
    
        return salvageValue;
    }
    
    int GetEstimatedLife()
    {
        int estimatedLife = 0;
    
        try
        {
            Write("Estimated Life: ");
            estimatedLife = int.Parse(ReadLine()!);
        }
        catch (Exception exc) when (exc is FormatException fe)
        {
            WriteLine("The value you provided for the machine cost cannot be used.");
            WriteLine("The error reported is: " + fe.Message);
        }
    
        return estimatedLife;
    }
    
    double cost    = GetMachineCost();
    double salvage = GetSalvageValue();
    int    life    = GetEstimatedLife();
    
    double depreciatiableAmount = cost - salvage;
    
    Clear();
    
    WriteLine("=-= Depreciation - Sum-of-the-Year's Digits =-=");
    WriteLine("===============================================");
    WriteLine("Depreciation Estimation");
    WriteLine("-----------------------------------------------");
    WriteLine("Machine Cost:             {0:N}", cost);
    WriteLine("Salvage Value:            {0:N}", salvage);
    WriteLine("Estimated Life:           {0}", life);
    WriteLine("depreciatiable Amount:    {0:N}", depreciatiableAmount);
    
    int year               = 1;
    int reverse            = 0;
    int sumOfYears         = (life * (life + 1)) / 2;
    double[] depreciations = new double[life];
    string[] fractions     = new string[life];
    
    for (int i = life - 1; i >= 0; i--)
    {
        fractions[reverse] = (i + 1) + "/" + sumOfYears;
        depreciations[reverse] = (depreciatiableAmount * (i + 1)) / sumOfYears;
        reverse++;
    }
    
    WriteLine("===============================================");
    WriteLine("Year        Fraction        Depreciation");
    WriteLine("-----------------------------------------------");
    
    for (int i = 0; i <= life - 1; i++)
    {
        WriteLine("{0,3}{1,15}{2,20}", year, fractions[i], Ceiling(@depreciations[i]));
        WriteLine("-----------------------------------------------");
    
        year++;
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging
  3. When requested, type the Machine Cost as 6,849.95 and press Enter
  4. Type the Salvage Value as 524.85 and press Enter
  5. Type the Estimated Life as 5 and press Enter:
    =-= Depreciation - Sum-of-the-Year's Digits =-=
    ===============================================
    Depreciation Estimation
    -----------------------------------------------
    Machine Cost:             6,849.95
    Salvage Value:            524.85
    Estimated Life:           5
    depreciatiable Amount:    6,325.10
    ===============================================
    Year        Fraction        Depreciation
    -----------------------------------------------
      1           5/15                2109
    -----------------------------------------------
      2           4/15                1687
    -----------------------------------------------
      3           3/15                1266
    -----------------------------------------------
      4           2/15                 844
    -----------------------------------------------
      5           1/15                 422
    -----------------------------------------------
    
    Press any key to close this window . . .
  6. To close the window, press Z, and return to your programming environment

For Each Item In a List

Instead of visiting the elements of a list by counting them, you may want to visit each item directly. To assist you with this, the C# language provides an operator named foreach. The formula to use it is:

foreach(variable in list) statement;

To make your code easy to read, you can (and should) write the statement on its own line. This can be done as follows:

foreach(variable in list)
statement;

The loop starts with the foreach keyword followed by parentheses. In the parentheses, enter the list that contains the elements you want. Precede that list with an operator named in. The foreach loop needs a variable that would represent an item from the list. Therefore, in the parentheses, start by declaring a variable before the in operator. Of course, the variable declared by a data type and a name. Outside the parentheses, create a statement of your choice. At a minimum, you can simply display the variable's value to the user. Here is an example:

int[] numbers = new int[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };

foreach (int n in numbers)
    Console.WriteLine("Number: {0}", n);

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

This would produce:

Number: 102
Number: 44
Number: 525
Number: 38
Number: 6
Number: 28
Number: 24481
Number: 327
Number: 632
Number: 104
===============================
Press any key to continue . . .

You can declare the variable with the var keyword. Here is an example:

using static System.Console;

string[] provinces = new string[] { "Saskatchewan", "British Columbia",
                                    "Ontario", "Alberta", "Manitoba" };

foreach (var administration in provinces)
    WriteLine("Province: {0}", administration);

WriteLine("===============================");

You can include the statement inside curly brackets. This is especially useful if you to execute more than one 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 a nesting. Here is an example:

int 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 (int 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.

Selecting a Value From a List

Introduction

If you have a list, such as an array, made of too many values, at one time you may want to isolate only the first n members of the list, or the last m members of the list, or a range of members from an index i to an index j. Another operation you may be interested to perform is to find out if a certain value exists in the list. One more interesting operation would be to find out what members or how many members of the list respond to a certain criterion.

for Looping

Consider the following array:

int[] numbers = new[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };

Imagine you want to access only the first n members of the array. To do this, you can use an if conditional statement nested in a for loop. Here is an example that produces the first 4 values of the array:

int[] numbers = new int[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };

for (int i = 0; i < 10; i++)
    if (i < 4)
        Console.WriteLine("Number: {0}", numbers[i]);

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

This would produce:

Number: 102
Number: 44
Number: 525
Number: 38
===============================
Press any key to continue . . .

You can use the same technique to get the last m members of a list. You can also use a similar technique to get one or a few values inside of the list, based on a condition of your choice. Here is an example that gets the values that are multiple of 5 from the array:

int[] numbers = new int[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };

for (int i = 0; i < 10; i++)
    if (numbers[i] % 5 == 0)
        Console.WriteLine("Number: {0}", numbers[i]);

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

This would produce:

Number: 525
===============================
Press any key to continue . . .

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 constant 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 constant 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 for ever. 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:

int 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-2024, FunctionX Friday 15 October 2021 Next