Loops C# Help

C# provides four different loops (for, while, do-while, and foreach) that allow you to execute a block of code repeatedly until a certain condition is met. The for, while, and. do …while loops are essentially identical to those encountered in C++.

The for Loop

C# for loops provide a mechanism for iterating through a loop where you test whether a particular condition holds before you perform another iteration. The syntax is

for (initializer; condition; iterator) 

statement(s)

where,

  1. The initializer is the expression evaluated before the first loop is executed (usually initializing a local variable as a loop counter).
  2.  The condition is the expression checked before each new iteration of the loop (this must evaluate to true for another iteration to be performed).
  3.  The iterator is an expression evaluated after each iteration (usually incrementing the loop counter).

The iterations end when the condition evaluates to false.

The for loop is a so-called pretest loop because the loop condition is evaluated before the loop statements are executed, and so the contents of the loop won’t be executed at all if the loop condition is false.

The for loop is excellent for repeating a statement or a block of statements for a predetermined number of times. The following example is typical of the use of a for loop. The following code will write out all the integers from 0 to 99.

Here, you declare an int called i and initialize it to zero. This·will’be used as the loop counter. You then immediately test whether it is less than 100. Because this condition evaluates to true, you execute
the code in the loop, displaying the value O.You then increment the counter by one, and walk through the proc.e.s•s again. Looping ends when i reaches 100.

Actually, the way the preceding loop is written isn’t quite how you would normally write it. C# has a shorthand for adding 1 to a variable, so instead of i = i + 1, you can simply write i++:

for (int i = 0; i < 100; i++)
(
// etc.

}

 C# for ‘loop syntax is far more powerful than the Visual Basic For … Next loop because the iterator can be any statement.In Visual Basic, all you can do is add or subtract some number from the loop control’ variable. In C# you can do anything; for example, you can multiply the loop control variable by 2. You can also make use of type inference for the iteration variable i in the preceding example. Using type inference the loop construct would be:

for (var i = 0; i < 100; i++)

It’s not unusual to nest for loops SO that an inner loop executes once completely for each iteration of an outer loop. This scheme is typically employed.to loop through every element in a rectangular multidimensional array. The outermost loop loops through every row, and the inner loop loops through every column in a particular row. The.following code displays rows of numbers. It also uses another Console method, Console. write ( ), which does the same as Console. writeLine ( ) but doesn’t a carriage return to ,the output.

Although j is an integer, it will be automatically converted to a string so that the concatenation can take place. C++ developers will note that this is far easier than string handling ever was in C++; for Visual
.Basic developers this is familiar ground.

C and C++ programmers should take note of one particular feature of the preceding example. The counter variable in the innermost loop is effectively re-declared with each successive iteration of the outer loop ,This syntax is legal not only in C# but in C++ as well.

The preceding sample results in this output:

csc NumberTable.cs

Microsoft (R) Visual C# Compiler version 9.00.20404 for Microsoft (R) .NET Framework version 3.5 Copyright (C) Microsoft Corporation. All rights reserved.

6    1    2   3   4   5    6  7   8   9
10  11 12 13 14 15 16 17 18 19
20  21 22 23 24 25 26 27 28 29
30  31 32 33 34 35 36 37 38 39
40  41 42 43 44 45 46 47 48 49
50  51 52 53 54 55 56 57 58 59
60  61 62 63 64 65 66 67 68 69
70  71 72 73 74 75 76 77 78 79
80  81 82 83 84 85 86 87 88 89
90  91 92 93 94 95 96 97 98 99

The while Loop

The while loop is identical to the while loop in C++ and Java, and the While. While loop in Visual Basic. Like the for loop, while is a pretest loop. The syntax is similar, but while loops take only one expression:

while (condition)
statement (s) ;

Unlike the for loop, the while loop is most often used to repeat a statement or a block of statements for a number of times that is not known before the loop begins. Usually, a statement inside the while loop’s body will set a Boolean flag to false on a certain iteration, triggering the end of the loop, as in the following example:

All of C#’s looping mechanisms, including the while loop, can forgo the curly braces that follow them if they intend to repeat just a single statement and not a block of statements. Again, many programmers
consider it good practice to use braces all of the time.

The do while Loop

The do while loop is the post-test version of the.while loop. it does the same thing with the same syntax as do while in C++ and Java, and the same thing as Loop. While in Visual Basic. This mew that the loop’s test condition is evaluated after the body of the loop has been executed. Consequently, do … while loops are useful for situations in which a block of statements must be . executed at least one time, as in this example:

 

The foreach Loop

The foreach loop is the final C# looping mechanism that we discuss. Whereas the other looping mechanisms were present in the earliest versions of C and C++, the foreach statement is a new addition (borrowed from Visual Basic), and a very welcome one at that.

The foreach loop allows you to iterate through each item in a collection. it is an object that contains other objects. Technically, to count as a collection, it must support an interface called IE numerable. Examples of collections include C# arrays, the collection classes in the System. Collection namespaces, and user-defined collection classes. You can get an idea of the syntax of foreach from the following code, if you assume that arrayOfInts is (unsurprisingly) an array of .ints:

Here, foreach steps through’ the array one element at a time. With each element, it’places the value if ..; the element in the int variable called temp and then performs an iteration of the loop.

Here is another situation where type inference can be used. The foreach loop would become:

foreach (var temp. in arrayOflnts)

temp would be inferred to int because that is what the collection item type is.

An important point to note with foreach is that you can’t change the value of the item in the collection (temp in the preceding code), so code such .as the following will not compile:

If you need to iterate through the items in a collection and change their values, you will need to use a for loop instead.

Posted on October 27, 2015 in C# Basics

Share the Story

Back to Top
Share This