Home

Details on Counting and Looping

Doing Something While a Condition is True

Introduction

The C# language supports various ways to keep checking a condition to take some action until a condition becomes false. In the previous lesson, we saw that one way to perform this operation is with the with keyword. We also saw that this with keyword by itself doesn't control the starting point of its operation. You need an external way to set that starting point. Fortunately, C# provides various options to address different issues related to counting and looping.

Practical LearningPractical Learning: Introducing Looping

  1. Start Microsoft Visual Studio and create a new Console application (.NET Framework) named DoubleDecliningBalance1
  2. Design the form as follows:

    Doing Something While a Condition is True

    Control (Name) Text TextAlign
    Label   Machine Cost:  
    TextBox txtMachineCost   Right
    Label   Estimated Life:  
    TextBox txtEstimatedLife   Right
    Label   Years  
    Button btnCalculate Calculate  
    Label   ____________  
    Label   Declining Rate:  
    TextBox txtDecliningRate   Right
    Label   %  
    ListView lvwDepreciation  
    View:          Details
    GridLines:     True
    FullRowSelect: True
    Anchor: Top, Bottom, Left, Right

    List View Columns

    (Name) Text TextAlign Width
    colYears Years   35
    colBeginningOfYear Book Value at Beginning of Year Center 170
    colDepreciationYear Depreciation for the Year Center 130
    colEndOfYear Book Value at End of Year Center 140
  3. On the form, double-click the Calculate button

do This while a Condition is True

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

do statement while (condition);

If the statement includes 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 it there is only one statement to exercute.

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:

If you are creating the condition in a method of a class, if the statement is long and should span more than one line, start it with an opening curly bracket "{" and end it with a closing curly bracket "}".

using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        int number = 0;
        
        do {
            WriteLine("Make sure you review the time sheet before submitting it.");
            
            number++;
        } while (number <= 4);

        WriteLine("==========================================================");
        return 1_000;
    }
};

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

Practical LearningPractical Learning: doing Something while a Condition is True

  1. Change the document as follows:
    using System;
    using System.Windows.Forms;
    
    namespace DoubleDecliningBalance1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                int    estimatedLife;
                double machineCost = 0.00;
    
                try
                {
                    machineCost = double.Parse(txtMachineCost.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must type a valid value that represents the " +
                                    "cost of the machine. Since you don't provide a " +
                                    "valid value, we will set the machine cost to 0.00.",
                                    "Depreciation: Straight-Line Method");
    
                    txtMachineCost.Text = "0.00";
                }
    
                try
                {
                    estimatedLife = int.Parse(txtEstimatedLife.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You didn't enter a valid number of years for the life of " +
                                    "the machine. Please correct it, otherwize, we will consider that this machine " +
                                    "has no life, or a life of 0 years.",
                                    "Depreciation: Straight-Line Method");
    
                    estimatedLife = 1;
                    txtEstimatedLife.Text = "1";
                }
    
                double decliningRate = (100.00 / estimatedLife) * 2.00;
    
                double[] yearlyDepreciations = new double[estimatedLife];
                double[] bookValuesEndOfYear = new double[estimatedLife];
                double[] bookValuesBeginningOfYear = new double[estimatedLife];
    
                int year = 1;
                // Year 1
                bookValuesBeginningOfYear[0] = machineCost;
                yearlyDepreciations[0] = machineCost * decliningRate / 100;
                bookValuesEndOfYear[0] = machineCost - yearlyDepreciations[0];
    
                int i = 1;
    
                // The other years
                do
                {
                    yearlyDepreciations[i] = bookValuesEndOfYear[i - 1] * decliningRate / 100;
                    bookValuesEndOfYear[i] = bookValuesEndOfYear[i - 1] - yearlyDepreciations[i];
                    bookValuesBeginningOfYear[i] = bookValuesEndOfYear[i - 1];
                    i++;
                } while (i <= estimatedLife - 1);
    
                i = 0;
    
                ListViewItem lviDepreciation = null;
    
                // Displaying the values
                txtDecliningRate.Text = decliningRate.ToString("F");
    
                lvwDepreciation.Items.Clear();
    
                do
                {
                    lviDepreciation = new ListViewItem(year.ToString());
    
                    lviDepreciation.SubItems.Add(Math.Ceiling(bookValuesBeginningOfYear[i]).ToString());
                    lviDepreciation.SubItems.Add(Math.Ceiling(yearlyDepreciations[i]).ToString());
                    lviDepreciation.SubItems.Add(Math.Ceiling(@bookValuesEndOfYear[i]).ToString());
    
                    lvwDepreciation.Items.Add(lviDepreciation);
    
                    i++;
                    year++;
                } while (i <= estimatedLife - 1);
            }
        }
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Loops and Lists

  3. Enter the following values:
    Machine Cost:  24680
    Estimated Life 8
  4. Click the Calculate button:

    Introduction to Loops and Lists

  5. Close the form and return to your programming environment
  6. Start a new Windows Forms App (.NET Framework) named CountriesStatistics2
  7. Design the form as follows:

    Doing Something While a Condition is True

    Control (Name) Text TextAlign
    Label   United Mexican States Font: Georgia, 20.25pt, style=Bold
    Label   ____________________________________  
    ListView lvwStates  
    View:          Details
    GridLines:     True
    FullRowSelect: True
    Anchor: Top, Bottom, Left, Right

    List View Columns

    (Name) Text TextAlign Width
    colNumber #   25
    colStateName State Name   100
    colCapital Capital   150
    colAreaSqrKms Area (Sqr Kms) Right 90
    colAreaSqrMiles Area (Sqr Ml) Right 80
    colAdmissionToFederation Admission to Federation Center 130
  8. Right-click the form and click View Code

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;

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:

using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        for (int number = 0; number <= 5; number++)
            WriteLine("The time sheet was checked and this payroll has been approved.");

        WriteLine("===============================================================");
        return 15_000_101;
    }
}

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.
The time sheet was checked and this payroll has been approved.
===============================================================
Press any key to continue . . .

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:

using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        int number;
        
        for (number = 0; number <= 5; number++)
            WriteLine("The time sheet was checked and this payroll has been approved.");

        WriteLine("===============================================================");
        return 15_000_101;
    }
}

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

using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        span class="codered">int number = 0;
        
        for (; number <= 5; number++)
            WriteLine("The time sheet was checked and this payroll has been approved.");

        WriteLine("===============================================================");
        return 15_000_101;
    }
}

Practical LearningPractical Learning: Counting for a Loop

  1. Change the document as follows:
    using System.Windows.Forms;
    
    namespace CountriesStatistics3
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
    
                Show();
            }
    
            void Show()
            {
                string[] states = new string[31];
    
                states[0]  = "Guanajuato";      states[1]  = "Tamaulipas";          states[2]  = "Michoacán";   states[3] = "Coahuila";
                states[4]  = "Chihuahua";       states[5]  = "Baja California Sur"; states[6]  = "Nayarit";     states[7] = "Puebla";
                states[8]  = "Oaxaca";          states[9]  = "Morelos";             states[10] = "Sonora";     states[11] = "Aguascalientes";
                states[12] = "Baja California"; states[13] = "Tabasco";             states[14] = "Jalisco";    states[15] = "México";
                states[16] = "Guerrero";        states[17] = "Colima";              states[18] = "Zacatecas";  states[19] = "Sinaloa";
                states[20] = "Campeche";        states[21] = "Quintana Roo";        states[22] = "Nuevo León"; states[23] = "Hidalgo";
                states[24] = "Tlaxcala";        states[25] = "Yucatán";             states[26] = "Querétaro";  states[27] = "Veracruz";
                states[28] = "San Luis Potosí"; states[29] = "Durango";             states[30] = "Chiapas";
    
                string[] capitals = new string[] { "Guanajuato",      "Ciudad Victoria",           "Morelia",
                                                   "Saltillo",        "Chihuahua",                 "La Paz",
                                                   "Tepic",           "Puebla de Zaragoza",        "Oaxaca de Juárez",
                                                   "Cuernavaca",      "Hermosillo",                "Aguascalientes",
                                                   "Mexicali",        "Villahermosa",              "Guadalajara",
                                                   "Toluca de Lerdo", "Chilpancingo de los Bravo", "Colima",
                                                   "Zacatecas",       "Culiacán",                  "San Francisco de Campeche",
                                                   "Chetumal",        "Monterrey",                 "Pachuca",
                                                   "Tlaxcala",        "Mérida",                    "Santiago de Querétaro",
                                                   "Xalapa",          "San Luis Potosí",           "Victoria de Durango", "Tuxtla Gutiérrez"};
                int[] areasSqrKms = new int[]   {   30608, 80175, 58643, 151563, 247455,  73922, 27815, 34290, 93793,   4893,
                                                   179503,  5618, 71446,  24738,  78599,  22357, 63621,  5625, 75539,  57377,
                                                    57924, 42361, 64220,  20846,   3991,  39612, 11684, 71820, 60983, 123451,  73289 };
                int[] areasSqrMiles = new int[] {   11818, 30956, 22642,  58519,  95543,  28541, 10739, 13240, 36214,   1889,
                                                    69306,  2169,  27585,  9551,  30347,   8632, 24564,  2172, 29166,  22153,
                                                    22365, 16356,  24800,  8049,   1541,  15294,  4511, 27730, 23546,  47665, 28297 };
                int[] ordersOfAdmissionToFederation = new int[] {  2,  14,   5,  16,  18,  31,  28,   4,   3,  27,
                                                                  12,  24,  29,  13,   9,   1,  21,  23,  10,  20,
                                                                  25,  30,  15,  26,  22,   8,  11,   7,   6,  17,  19 };
    
                ListViewItem lviState = null;
    
                for(int i = 0; i < states.Length; i++)
                {
                    lviState = new ListViewItem((i + 1).ToString());
    
                    lviState.SubItems.Add(states[i]);
                    lviState.SubItems.Add(capitals[i].ToString());
                    lviState.SubItems.Add(areasSqrKms[i].ToString());
                    lviState.SubItems.Add(areasSqrMiles[i].ToString());
                    lviState.SubItems.Add(ordersOfAdmissionToFederation[i].ToString());
    
                    lvwStates.Items.Add(lviState);
                }
            }
        }
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Counting for a Loop

  3. Close the form and return to your programming environment
  4. Start a new Windows Forms application (.NET Framework) named SumOfTheYearsDigits1
  5. Design the form as follows:

    Doing Something While a Condition is True

    Control (Name) Text TextAlign
    Label   Machine Cost:  
    TextBox txtMachineCost   Right
    Label   Salvage Value:  
    TextBox txtSalvageValue   Right
    Label   Estimated Life:  
    TextBox txtEstimatedLife   Right
    Label   Years  
    Button btnCalculate Calculate  
    Label   ____________  
    Label   Depreciable Amount:  
    TextBox txtDepreciableAmount   Right
    Label   %  
    ListView lvwDepreciation  
    View:          Details
    GridLines:     True
    FullRowSelect: True
    Anchor: Top, Bottom, Left, Right

    List View Columns

    (Name) Text TextAlign Width
    colYears Years  
    colFraction Fraction Center 100
    colDepreciation Depreciation Center 125
  6. On the form, double-click the Calculate button

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, fir 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 System;
    using System.Windows.Forms;
    
    namespace SumOfTheYearsDigits1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                int    estimatedLife;
                double machineCost = 0.00;
                double salvageValue = 0.00;
    
                try
                {
                    machineCost = double.Parse(txtMachineCost.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must type a valid value that represents the " +
                                    "cost of the machine. Since you don't provide a " +
                                    "valid value, we will set the machine cost to 0.00.",
                                    "Depreciation: Straight-Line Method");
    
                    txtMachineCost.Text = "0.00";
                }
    
                try
                {
                    salvageValue = double.Parse(txtSalvageValue.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must provide a value you estimate the machine  " +
                                    "will have at the end of the cycle (or the end of its " +
                                    "life cycle). If you don't enter a valid value, we will " +
                                    "consider the estimated end value to 0.00.",
                                    "Depreciation: Straight-Line Method");
    
                    txtSalvageValue.Text = "0.00";
                }
    
                try
                {
                    estimatedLife = int.Parse(txtEstimatedLife.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You didn't enter a valid number of years for the life of " +
                                    "the machine. Please correct it, otherwize, we will consider " +
                                    "that this machine has no life, or a life of 0 years.",
                                    "Depreciation: Straight-Line Method");
    
                    estimatedLife = 1;
                }
    
    
                int year = 1;
                int reverse = 0;
                int sumOfYears = (estimatedLife * (estimatedLife + 1)) / 2;
                double[] depreciations = new double[estimatedLife];
                string[] fractions = new string[estimatedLife];
    
                double depreciatiableAmount = machineCost - salvageValue;
    
                txtDepreciatiableAmount.Text = depreciatiableAmount.ToString("F");
    
                for (int i = estimatedLife - 1; i >= 0; i--)
                {
                    fractions[reverse] = (i + 1) + "/" + sumOfYears;
                    depreciations[reverse] = (depreciatiableAmount * (i + 1)) / sumOfYears;
                    reverse++;
                }
    
                ListViewItem lviDepreciation = null;
    
                lvwDepreciation.Items.Clear();
    
                for (int i = 0; i <= @estimatedLife - 1; i++)
                {
                    lviDepreciation = new ListViewItem(year.ToString());
                    lviDepreciation.SubItems.Add(fractions[i].ToString());
                    lviDepreciation.SubItems.Add(Math.Ceiling(depreciations[i]).ToString());
    
                    lvwDepreciation.Items.Add(lviDepreciation);
                    
                    year++;
                }
            }
        }
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Loops and Lists

  3. Enter the values as follows:
    Machine Cost: 6850
    Salvage Value: 500
    Estimated Life 8

    Introduction to Loops and Lists

  4. Click the Calculate button:

    Introduction to Loops and Lists

  5. Close the form and return to your programming environment

For Each Item In a List

Inseead 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;

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:

using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        int[] numbers = new int[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };

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


        WriteLine("===============================");
        return 22_813_729;
    }
}

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;

public class Exercise
{
    public static int Main(string[] args)
    {
        string[] provinces = new string[] { "Saskatchewan", "British Columbia",
                                            "Ontario", "Alberta", "Manitoba" };

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

        WriteLine("===============================");
        return 22_813_729;
    }
}

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:

using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        int number = 0;

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

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

            number++;
        }

        WriteLine("===============================================================");
        return 15_000_101;
    }
}

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:

using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        for (int number = 0; number <= 5; number++)
        {
            WriteLine("The time sheet was checked and this payroll has been approved.");

            if (number == 2)
                break;
        }

        WriteLine("===============================================================");
        return 15_000_101;
    }
}

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:

using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        string strNumbers = "";

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

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

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

        WriteLine("===========================================");
        return 15_000_101;
    }
}

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:

using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        string strNumbers = "";

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

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

        WriteLine("The list of numbers is {0}", strNumbers);
        WriteLine("===========================================");
        return 22_813_729;
    }
}

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:

public class Exercise
{
    public static int Main(string[] args)
    {
        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:

using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        int[] numbers = new int[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };

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

        WriteLine("===============================");
        return 22_813_729;
    }
}

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:

using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        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)
                WriteLine("Number: {0}", numbers[i]);

        WriteLine("===============================");
        return 22_813_729;
    }
}

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 juste the true Boolean constant in the parentheses of true. Here is an example:

using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        while (true)
            WriteLine("Application development is fun!!!");

        return 22_813_729;
    }
}

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:

using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        int i = 0;

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

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

            i++;
        }

        WriteLine("===============================");
        return 22_813_729;
    }
}

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.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2020, FunctionX Next