﻿ Lesson 02: Counting and Looping

Introduction to Counting and Looping

Overview

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

• You must indicate when and how the loop will start
• You must indicate what condition will make the loop stop. After all, you don't want a loop that never stops. This could cause the application to crash (such if/when the computer runs out of memory)
• You must indicate under what condition the loop will change from one state or step to the other, usually from one state or step to the next Practical Learning: Introducing Looping

1. Start Microsoft Visual Studio
2. On the main menu, click File -> New -> Project...
3. In the New Project dialog box, click Empty Project (.NET Framework) and set the Name to SweetStarClothiers1
4. Click OK
5. In the Solution Explorer, right-click SweetStarClothiers1 -> Add -> Class...
6. Type SweetStarClothiers as the name of the class
8. Change the document as follows:
```using static System.Console;

namespace SweetStarClothiers1
{
public class SweetStarClothiers
{
public static int Main()
{
WriteLine("=-=  Depreciation - Straight-Line Method  =-=");
WriteLine("----------------------------------------------");
WriteLine("Provide the following values about the machine");
Write("Machine Cost:   ");
double machineCost = int.Parse(ReadLine());
Write("Salvage Value:  ");
double salvageValue = double.Parse(ReadLine());
Write("Estimated Life: ");
int estimatedLife = int.Parse(ReadLine());

double depreciatiableAmount = machineCost - salvageValue;
double depreciationRate = 100 / estimatedLife;
double yearlyDepreciation = depreciatiableAmount / estimatedLife;

Clear();

WriteLine("=-=  Depreciation - Straight-Line Method  =-=");
WriteLine("==============================================");
WriteLine("Depreciation Estimation");
WriteLine("--------------------------------------");
WriteLine("Machine Cost:        {0}", machineCost);
WriteLine("Salvage Value:       {0}", salvageValue);
WriteLine("Estimated Life:      {0}", salvageValue);
WriteLine("Depreciation Rate:   {0}", depreciationRate);
WriteLine("Depreciable Amount:  {0}", depreciatiableAmount);
WriteLine("Yearly Depreciation: {0}", yearlyDepreciation);
WriteLine("==============================================");

return 0;
}
}
}```
9. To execute the application, on the main menu, click Debug -> Start Without Debugging:
```=-=  Depreciation - Straight-Line Method  =-=
----------------------------------------------
Provide the following values about the machine
Machine Cost:```
10. Type some values as follows:
```=-=  Depreciation - Straight-Line Method  =-=
----------------------------------------------
Provide the following values about the machine
Machine Cost:   17000
Salvage Value:  5000
Estimated Life: 5```
11. Press Enter:
```=-=  Depreciation - Straight-Line Method  =-=
==============================================
Depreciation Estimation
--------------------------------------
Machine Cost:        17000
Salvage Value:       5000
Estimated Life:      5000
Depreciation Rate:   20
Depreciable Amount:  12000
Yearly Depreciation: 2400
==============================================
Press any key to continue . . .```
12. Press Enter to close the window and return to your programming environment

Introduction to Lists and Arrays

A list is a group of items. Here is an example:

```public class Exercise
{
public static int Main()
{
double number1 = 12.44;
double number2 = 525.38;
double number3 = 6.28;
double number4 = 2448.32;
double number5 = 632.04;

return 0;
}
}```

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

```public class Exercise
{
public static int Main()
{
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

return 0;
}
}```

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:

```public class Exercise
{
public static int Main()
{
double[] numbers = new double { 12.44, 525.38, 6.28, 2448.32, 632.04 };

return 0;
}
}```

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

```using static System.Console;

public class Exercise
{
public static int Main()
{
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

WriteLine("Number of Items: " + numbers.Length);
WriteLine("==================================");
return 0;
}
}```

This would produce:

```Number of Items: 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 access each of the items:

```using static System.Console;

public class Exercise
{
public static int Main()
{
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

WriteLine("Number: " + numbers);
WriteLine("Number: " + numbers);
WriteLine("Number: " + numbers);
WriteLine("Number: " + numbers);
WriteLine("Number: " + numbers);
WriteLine("----------------------");
WriteLine("Number of Items: " + numbers.Length);

WriteLine("==================================");
return 0;
}
}```

This would produce:

```Number: 12.44
Number: 525.38
Number: 6.28
Number: 2448.32
Number: 632.04
----------------------
Number of Items: 5
==================================
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:

```public class Exercise
{
public static void Main()
{
int counter = 0;
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
}
}```

While Looping

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

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

If you are writing your code in a webpage, start the statement with the @ symbol. Also, the statement(s) must be included in curly brackets:

```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: Most of the time, before entering in a while loop, you should have an object or a variable that has been initialized or 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:

```using static System.Console;

public class Exercise
{
public static int Main()
{
// Consider a starting value as 0
int number = 0;

while (number <= 5)
{
// As long as the above value is lower than 5, ...
// ... display that number
WriteLine("Make sure you review the time sheet before submitting it.");

// Increase the number (or counter)
number++;
// Check the number (or counter again. Is it still less than 4?
}

WriteLine("===========================================================");
return 0;
}
}```

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

```using static System.Console;

public class Exercise
{
public static int Main()
{
int number = 5;

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

number++;
}

WriteLine("===========================================================");
return 0;
}
}```

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.

While in an Array

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:

```using static System.Console;

public class Exercise
{
public static int Main()
{
int counter = 0;
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

while (counter <= 4)
{
WriteLine("Number: " + numbers[counter]);

counter++;
}

WriteLine("----------------------");
WriteLine("Number of Items: " + numbers.Length);
WriteLine("==================================");
return 0;
}
}```

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:

```using System;

public class Exercise
{
public static int Main()
{
int counter = 0;
Random rndNumber = new Random();
double[] numbers = new double;

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

counter++;
}

counter = 0;

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

counter++;
}

Console.WriteLine("----------------------");
Console.WriteLine("Number of Items: " + numbers.Length);
Console.WriteLine("==================================");
return 0;
}
}```

This would produce:

```Number: 12.44
Number: 525.38
Number: 6.28
Number: 2448.32
Number: 632.04
----------------------
Number of Items: 5
==================================
Press any key to continue . . .``` Practical Learning: Introducing Loops in Lists

1. Change the SweetStarClothiers,cs document as follows:
```using static System.Console;

namespace SweetStarClothiers1
{
public class SweetStarClothiers
{
private static void Main()
{
WriteLine("=-=  Depreciation - Straight-Line Method  =-=");
WriteLine("----------------------------------------------");
WriteLine("Provide the following values about the machine");
Write("Machine Cost:   ");
double machineCost = int.Parse(ReadLine());
Write("Salvage Value:  ");
double salvageValue = double.Parse(ReadLine());
Write("Estimated Life: ");
int estimatedLife = int.Parse(ReadLine());

double depreciatiableAmount = machineCost - salvageValue;
double depreciationRate = 100 / estimatedLife;
double yearlyDepreciation = depreciatiableAmount / estimatedLife;

Clear();

WriteLine("=-=  Depreciation - Straight-Line Method  =-=");
WriteLine("==============================================");
WriteLine("Depreciation Estimation");
WriteLine("--------------------------------------");
WriteLine("Machine Cost:        {0}", machineCost);
WriteLine("Salvage Value:       {0}", salvageValue);
WriteLine("Estimated Life:      {0}", salvageValue);
WriteLine("Depreciation Rate:   {0}", depreciationRate);
WriteLine("Depreciable Amount:  {0}", depreciatiableAmount);
WriteLine("Yearly Depreciation: {0}", yearlyDepreciation);

int i = 1;
int year = 1;
double[] bookValues = new double[estimatedLife + 1];
bookValues = machineCost;

WriteLine("-----------------------------------------");

while (i <= estimatedLife - 1)
{
bookValues[i] = bookValues[i - 1] - yearlyDepreciation;
i++;
}

i = 0;
bookValues[estimatedLife] = salvageValue;

WriteLine("==============================================");
WriteLine("Year   Book Value    Accumulated Distribution");
WriteLine("----------------------------------------------");

while (i <= estimatedLife - 1)
{
double accumulatedDepreciation = yearlyDepreciation * year;
WriteLine("{0,3}{1,12}{2,20}", year, bookValues[i], accumulatedDepreciation);
WriteLine("----------------------------------------------");

i++;
year++;
}
}
}
}```
2. To execute the application, on the main menu, click Debug -> Start Without Debugging:
```=-=  Depreciation - Straight-Line Method  =-=
----------------------------------------------
Provide the following values about the machine
Machine Cost:```
3. Type some values as follows:
```=-=  Depreciation - Straight-Line Method  =-=
----------------------------------------------
Provide the following values about the machine
Machine Cost:   8500
Salvage Value:  1500
Estimated Life: 10```
4. Press Enter:
```=-=  Depreciation - Straight-Line Method  =-=
==============================================
Depreciation Estimation
--------------------------------------
Machine Cost:        8500
Salvage Value:       1500
Estimated Life:      1500
Depreciation Rate:   10
Depreciable Amount:  7000
Yearly Depreciation: 700
-----------------------------------------
==============================================
Year   Book Value    Accumulated Distribution
----------------------------------------------
1        8500                 700
----------------------------------------------
2        7800                1400
----------------------------------------------
3        7100                2100
----------------------------------------------
4        6400                2800
----------------------------------------------
5        5700                3500
----------------------------------------------
6        5000                4200
----------------------------------------------
7        4300                4900
----------------------------------------------
8        3600                5600
----------------------------------------------
9        2900                6300
----------------------------------------------
10        2200                7000
----------------------------------------------
Press any key to continue . . .```
5. Press Enter to close the window and return to your programming environment

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 condition is written directly in a webpage, you should start it with an @ symbol. Also, the statement(s) must be included inside curly brackets:

```do {
statement
} while (condition);```

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

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 "}". Here is an example:

```using System;

public class Exercise
{
public static int Main()
{
int number = 0;

do {
Console.WriteLine("Make sure you review the time sheet before submitting it.");

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

Console.WriteLine("===========================================================");
return 0;
}
}```

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.
Make sure you review the time sheet before submitting it.
===========================================================
Press any key to continue . . .``` Practical Learning: doing Something while a Condition is True

1. Change the code of the SweetStarClothiers.cs document as follows:
```using static System.Math;
using static System.Console;

namespace SweetStarClothiers1
{
public class SweetStarClothiers
{
public static int Main()
{
WriteLine("=-= Depreciation - Double Declining Balance =-=");
WriteLine("----------------------------------------------");
WriteLine("Provide the following values about the machine");
Write("Machine Cost:   ");
double machineCost = int.Parse(ReadLine());
Write("Salvage Value:  ");
double salvageValue = double.Parse(ReadLine());
Write("Estimated Life: ");
int estimatedLife = int.Parse(ReadLine());

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}", machineCost);
WriteLine("Salvage Value:           {0}", salvageValue);
WriteLine("Estimated Life:          {0}", estimatedLife);
WriteLine("Declining Rate:          {0}", decliningRate);
WriteLine("Depreciation First Year: {0}", depreciation);

int i = 1;
int year = 1;
double[] yearlyDepreciations = new double[estimatedLife];
double[] bookValuesEndOfYear = new double[estimatedLife];
double[] bookValuesBeginningOfYear = new double[estimatedLife];

// Year 1
bookValuesBeginningOfYear = machineCost;
yearlyDepreciations = machineCost * decliningRate / 100;
bookValuesEndOfYear = machineCost - yearlyDepreciations;

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

WriteLine("-----------------------------------------------------------");
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);

return 0;
}
}
}```
2. To execute the application, on the main menu, click Debug -> Start Without Debugging:
```=-= Depreciation - Double Declining Balance =-=
----------------------------------------------
Provide the following values about the machine
Machine Cost:```
3. Type some values as follows:
```=-= Depreciation - Double Declining Balance =-=
----------------------------------------------
Provide the following values about the machine
Machine Cost:   24680
Salvage Value:  0
Estimated Life: 8```
4. Press Enter:
```=-= Depreciation - Double Declining Balance =-=
==============================================
Depreciation Estimation
----------------------------------------------
Machine Cost:            24680
Salvage Value:           0
Estimated Life:          8
Declining Rate:          25
Depreciation First Year: 6170
-----------------------------------------------------------
Book Value at                              Book Value at
Beginning of Year   Depreciation for Year    End of Year
-----------------------------------------------------------
1                 24680                6170
-----------------------------------------------------------
2                 18510                4628
-----------------------------------------------------------
3                 13883                3471
-----------------------------------------------------------
4                 10412                2603
-----------------------------------------------------------
5                  7809                1953
-----------------------------------------------------------
6                  5857                1465
-----------------------------------------------------------
7                  4393                1099
-----------------------------------------------------------
8                  3295                 824
-----------------------------------------------------------
Press any key to continue . . .```
5. Press Enter to close the window and return to your programming environment

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 you are writing your code in a method of a class and if the stement can fit on one line, you can follow the above formula
• If you are writing your code in a webpage, if the statement(s) need many lines of code, in fact even if the statement is for one line of code, include it in curly brackets
• If you are writing your code in a webpage, precede it with the @ symbol

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

public class Exercise
{
public static int Main()
{
for(int number = 0; number <= 5; number++)
{
Console.WriteLine("Make sure you review the time sheet before submitting it.");
}

Console.WriteLine("===========================================================");
return 0;
}
}```

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

public class Exercise
{
public static int Main()
{
int number;

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

Console.WriteLine("===========================================================");
return 0;
}
}``` Practical Learning: Counting for a Loop

1. Change the code of the SweetStarClothiers.cs document as follows:
```using static System.Math;
using static System.Console;

namespace SweetStarClothiers1
{
public class SweetStarClothiers
{
public static int Main()
{
WriteLine("=-= Depreciation - Sum-of-the-Year's Digits =-=");
WriteLine("----------------------------------------------");
WriteLine("Provide the following values about the machine");
Write("Machine Cost:   ");
double machineCost = int.Parse(ReadLine());
Write("Salvage Value:  ");
double salvageValue = double.Parse(ReadLine());
Write("Estimated Life: ");
int estimatedLife = int.Parse(ReadLine());

double depreciatiableAmount = machineCost - salvageValue;

Clear();

WriteLine("=-= Depreciation - Sum-of-the-Year's Digits =-=");
WriteLine("==============================================");
WriteLine("Depreciation Estimation");
WriteLine("----------------------------------------------");
WriteLine("Machine Cost:          {0}", machineCost);
WriteLine("Salvage Value:         {0}", salvageValue);
WriteLine("Estimated Life:        {0}", estimatedLife);
WriteLine("depreciatiable Amount: {0}", depreciatiableAmount);

int year = 1;
int reverse = 0;
int sumOfYears = (estimatedLife * (estimatedLife + 1)) / 2;
double[] depreciations = new double[estimatedLife];
string[] fractions = new string[estimatedLife];

for (int i = estimatedLife - 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 <= @estimatedLife - 1; i++)

{
WriteLine("{0,3}{1,10}{2,14}", year, fractions[i], Ceiling(@depreciations[i]));
WriteLine("-------------------------------");

year++;
}

return 0;
}
}
}```
2. To execute the application, on the main menu, click Debug -> Start Without Debugging:
```=-= Depreciation - Sum-of-the-Year's Digits =-=
----------------------------------------------
Provide the following values about the machine
Machine Cost:```
3. Type some values as follows:
```=-= Depreciation - Sum-of-the-Year's Digits =-=
----------------------------------------------
Provide the following values about the machine
Machine Cost:   6850
Salvage Value:  500
Estimated Life: 8```
4. Press Enter:
```=-= Depreciation - Sum-of-the-Year's Digits =-=
==============================================
Depreciation Estimation
----------------------------------------------
Machine Cost:          6850
Salvage Value:         500
Estimated Life:        8
depreciatiable Amount: 6350
===============================
Year   Fraction    Depreciation
-------------------------------
1      8/36          1412
-------------------------------
2      7/36          1235
-------------------------------
3      6/36          1059
-------------------------------
4      5/36           882
-------------------------------
5      4/36           706
-------------------------------
6      3/36           530
-------------------------------
7      2/36           353
-------------------------------
8      1/36           177
-------------------------------
Press any key to continue . . .```
5. Press Enter to close the window and 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, 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;`

Here is an example:

```using System;

public class Exercise
{
public static int Main()
{
int number;

for (number = 5; number >= 0; number--)
{
Console.WriteLine("Make sure you review the time sheet before submitting it.");
}

Console.WriteLine("===========================================================");
return 0;
}
}```

For an Indexed Member of the Array

We saw how you can use the square brackets to access each member of the array one at a time. That technique allows you to access one, a few, or each member. If you plan to access all members of the array instead of just one or a few, you can use the for loop. The formula to follow is:

`for(DataType Initializer; EndOfRange; Increment) Do What You Want;`

In this formula, the for keyword, the parentheses, and the semi-colons are required. The data-type factor is used to specify how you will count the members of the array.

The Initializer specifies how you would indicate the starting of the count. As seen in Lesson 12, this initialization could use an initialized int-based variable.

The EndOfRange specifies how you would stop counting. If you are using an array, it should combine a conditional operation (<, <=, >, >=, or !=) with the number of members of the array minus 1.

The Increment factor specifies how you would move from one index to the next.

Here is an example:

```using System;

public class Exercise
{
static int Main()
{
var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

for (var i = 0; i < 5; i++)
Console.WriteLine(numbers[i]);

return 0;
}
}```

This would produce:

```12.44
525.38
6.28
2448.32
632.04
Press any key to continue . . .```

When using a for loop, you should pay attention to the number of items you use. If you use a number n less than the total number of members - 1, only the first n members of the array would be accessed. Here is an example:

```using System;

public class Exercise
{
static int Main()
{
var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

for (var i = 0; i < 3; i++)
Console.WriteLine("Number: {0}", numbers[i]);

return 0;
}
}```

This would produce:

```Number: 12.44
Number: 525.38
Number: 6.28
Press any key to continue . . .```

On the other hand, if you use a number of items higher than the number of members minus one, the compiler would throw an IndexOutOfRangeException exception. Here is an example:

```using System;

public class Exercise
{
static int Main()
{
var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

for (var i = 0; i < 12; i++)
Console.WriteLine("Number: {0}", numbers[i]);

return 0;
}
}```

This would produce: Therefore, when the number of items is higher than the number of members - 1, the compiler may process all members. Then, when it is asked to process members beyond the allowed range, it finds out that there is no other array member. So it gets upset.

You could solve the above problem by using exception handling to handle an IndexOutOfRangeException exception. Here is an example:

```using System;

public class Exercise
{
static int Main()
{
var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

try
{
for (var i = 0; i < 12; i++)
Console.WriteLine("Number: {0}", numbers[i]);
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("You tried to access values beyond " +
"the allowed range of the members of the array.");
}

return 0;
}
}```

This would produce:

```Number: 12.44
Number: 525.38
Number: 6.28
Number: 2448.32
Number: 632.04
You tried to access values beyond the allowed range of the members of the array.

Press any key to continue . . .```

This solution should not be encouraged. Fortunately, C# and the .NET Framework provide better solutions.

Selecting a Value From an Array

Because an array is a list of items, it could include values that are not useful in all scenarios. For example, having an array made of too many values, at one time you may want to isolate only the first n members of the array, or the last m members of the array, 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 this or that value exists in the array. One more interesting operation would be to find out what members or how many members of the array respond to this or that criterion. All these operations are useful and possible with different techniques.

Consider the following program:

```using System;

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

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

return 0;
}
}```

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

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 or a foreach loop. Here is an example that produces the first 4 values of the array:

```using System;

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

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

return 0;
}
}```

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 the array. You can also use a similar technique to get one or a few values inside of the array, based on a condition of your choice. Here is an example that gets the values that are multiple of 5 from the array:

```using System;

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

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

return 0;
}
}```

This would produce:

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

For Each Member in the Array

In a for loop, you should know the number of members of the array. If you do not, the C# language allows you to let the compiler use its internal mechanism to get this count and use it to know where to stop counting. To assist you with this, C# provides the foreach operator. To use it, the formula to follow is:

`foreach (type identifier in expression) statement`

The foreach and the in keywords are required.

The first factor of this syntax, type, can be var or the type of the members of the array. It can also be the name of a class as we will learn in Lesson 23.

The identifier factor is a name of the variable you will use.

The expression factor is the name of the array variable.

The statement is what you intend to do with the identifier or as a result of accessing the member of the array.

Like a for loop that accesses all members of the array, the foreach operator is used to access each array member, one at a time. Here is an example:

```using System;

public class Exercise
{
static int Main()
{
var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

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

return 0;
}
}```

This would produce:

```Employees Records
Employee Name: Joan Fuller
Employee Name: Barbara Boxen
Employee Name: Paul Kumar
Employee Name: Bertrand Entire```

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

public class Exercise
{
public static int Main()
{
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("===========================================================");
return 0;
}
}```

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

public class Exercise
{
public static int Main()
{
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("==============================================================");
return 0;
}
}```

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

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

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

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

Console.WriteLine("The list of numbers is " + strNumbers);
}

Console.WriteLine("==============================================================");
return 0;
}
}```

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.

Going to a Designated Label

The goto statement allows a program execution to jump to another section of the function in which it is being used. In order to use the goto statement, insert a name on a particular section of your function so you can refer to that name. The name, also called a label, is made of one word and follows the rules we have learned about C++ names (the name can be anything), then followed by a colon. Here is an example where the program is supposed to count the levels of a 14 story building:

```using System;

public class Exercise
{
public static int Main()
{
for (var stories = 1; stories <= 14; stories++)
{
if (stories == 4)
goto CountUpTo3;
Console.WriteLine("Story {0}", stories);
}

CountUpTo3:
Console.WriteLine("Our homes have only up to 3 levels\n");

return 0;
}
}```

This would produce:

```Story 1
Story 2
Story 3
Our homes have only up to 3 levels

Press any key to continue . . .```

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

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

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

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

Console.WriteLine("The list of numbers is " + strNumbers);

Console.WriteLine("==============================================================");
return 0;
}
}```

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

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.

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:

```using System;

public class Exercise
{
public static int Main()
{
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: " + numbers[i]);
}
}

Console.WriteLine("================================");
return 0;
}
}```

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

public class Exercise
{
public static int Main()
{
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: " + numbers[i]);
}
}

Console.WriteLine("================================");
return 0;
}
}```

This would produce:

```Number: 525
================================
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 tag so that, if the tag gets to a certain value, 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 System;

public class Exercise
{
static int Main()
{
for (var story = 0; story < 15; story++)
{
if (story == 6)
story = 10;
Console.WriteLine("Elevator at: {0}", story);
}

return 0;
}
}```

This would produce:

```Elevator at: 0
Elevator at: 1
Elevator at: 2
Elevator at: 3
Elevator at: 4
Elevator at: 5
Elevator at: 10
Elevator at: 11
Elevator at: 12
Elevator at: 13
Elevator at: 14
Press any key to continue . . .```

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

while(true)

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

```using System;

public class Exercise
{
public static int Main()
{
while(true)
{
Console.WriteLine("Web Development Programming 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 questions are, what is "this"?, and what is true? 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 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 System;

public class Exercise
{
public static int Main()
{
int i = 0;

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

Console.WriteLine("Web Development Programming is fun!!!");

i++;
}

Console.WriteLine("================================");
return 0;
}
}```

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 Learning: Ending the Lesson

• Close your programming environment