Fundamentals of Counting in Looping

Introduction

We have already been introduced to counting values and looping using some C# keywords. The concepts also applies to a list of values such as an array.

Practical LearningPractical Learning: Introducing Looping

  1. Start Microsoft Visual Studio
  2. Create a new Console App named StraightLineMethod1
  3. 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("====================================");
  4. To execute and test the application, on the main menu, click Debug -> Start Without Debugging
  5. At the requests, type the following values and press Enter after typing each value:
    Machine Cost:   22580
    Salvage Cost:   3875
    Estimated Life: 5
  6. 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 . . .
  7. Return to your programming environment

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:

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

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 = [ 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...
  7. Create a new C# Console App named DoubleDecliningBalance1
  8. In the Solution Explorer, right-click Program.cs and click Rename
  9. Type DepreciationEvaluation (to get DepreciationEvaluation.cs)
  10. 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;
float[] numbers = new float[] { 12.44f, 525.38f, 6.28f, 2448.32f, 632.04f };

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 float[]
                      {
                          12.44f, 525.38f, 6.28f, 2448.32f, 632.04f
                      }[counter]);

    counter++;
}

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

Or like this:

int counter = 0;

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

    counter++;
}

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

Or like this:

int counter = 0;

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

    counter++;
}

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

Doing Something While 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;
float[] numbers = new float[] { 12.44F, 525.38F, 6.28F, 2448.32F, 632.04F };

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;
float[] numbers = new float[] { 12.44F, 525.38F, 6.28F, 2448.32F, 632.04F };

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 float[]
                      {
                          12.44F, 525.38F, 6.28F, 2448.32F, 632.04F
                      }[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 named SumYearsDigits1
  6. In the Solution Explorer, right-click Program.cs and click Rename
  7. Type SumYearsDigits (to get SumYearsDigits.cs)
  8. Press Enter

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;
    }
    
    ubyte GetEstimatedLife()
    {
        ubyte estimatedLife = 0;
    
        try
        {
            Write("Estimated Life: ");
            estimatedLife = ubyte.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();
    ubyte 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 (ubyte 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(ubyte 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;
    }
    
    ubyte GetEstimatedLife()
    {
        ubyte estimatedLife = 0;
    
        try
        {
            Write("Estimated Life: ");
            estimatedLife = ubyte.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();
    ubyte    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(ubyte 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(ubyte 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:

ushort[] 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 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.

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:

ushort[] numbers = new ushort[] { 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:

ushort[] numbers = new ushort[] { 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 . . .

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2026, FunctionX Wednesday 15 October 2025, 08:45 Next