C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
These can be used as indexes of an array, or just for a numeric algorithm. For-loops are ideal here.
With an iteration variable, for-loops begin at a certain value and end at another. They pass through a range of numbers. For is versatile and fast.
A for-loop. Here, the name of the variable "i" is a convention. It is easier for other programmers to understand than unusual variable names.
Start: The loop starts at the value 0. In C# most collections are zero-based, so the first element is at 0.
End: The loop continues running through the body until "i" equals 10 (or some other value if it is set elsewhere).
Increment: Please note the third clause in the for-loop, the i++ part. This is the iteration statement—it occurs after each pass.
Based on: .NET 4.5 C# program that uses increment loop using System; class Program { static void Main() { for (int i = 0; i < 10; i++) { Console.WriteLine(i); } } } Output 0 1 2 3 4 5 6 7 8 9
Decrement loop. This is a simple example. A for-loop can decrement in the step condition. Here we start at 10, and continue until 0 is reached.
C# program that uses decrement loop using System; class Program { static void Main() { for (int i = 10 - 1; i >= 0; i--) { Console.WriteLine(i); } } } Output 9 8 7 6 5 4 3 2 1 0
Iteration step. The third clause in the for-loop is the step. This can change the variable (or any variable) by any amount—a constant is not even needed.
Two: Here we add two after each pass through the loop. So we skip odd number indexes.
C# program that uses step increment loop using System; class Program { static void Main() { for (int i = 0; i < 10; i += 2) { Console.WriteLine(i); } } } Output 0 2 4 6 8
Decrement, step. This program revisits loop decrementing. It decreases the iteration variable by two each time. The example is simple and straightforward.
C# program that uses step decrement loop using System; class Program { static void Main() { for (int i = 10 - 1; i >= 0; i -= 2) { Console.WriteLine(i); } } } Output 9 7 5 3 1
Expression, maximum bound. Complex expressions, even method calls, can be used in the conditions of a for-loop. This can help simplify code.
However: Be careful not to call an expensive function too much. Unneeded operations can end up executing.
C# program that uses expression in maximum bounds using System; class Program { static void Main() { for (int i = 0; i < (20 / 2); i += 2) { Console.WriteLine(i); } } } Output 0 2 4 6 8
First part. When a for-loops is encountered, the first of the three statements is executed. The for-loop shown first has its "int i = 0" statement executed.
Tip: We can start a for-loops with any value for the iteration variable. The value does not need to be a constant.
Second part: Evaluated before the first iteration, and after each execution. If this is true, the loop proceeds. If false, it stops.
Third part: Specifies how the iteration variable (i) changes after each successful iteration.
Chars. A for-loop often uses an int index. But other index types are possible. Here I use a char variable and loop over all the lowercase letters.
Tip: Often a for-loop over chars is useful for initializing a lookup table. Each char is accessed separately.
C# program that uses for, char range using System; class Program { static void Main() { // ... Loop over character range. for (char c = 'a'; c <= 'z'; c++) { Console.WriteLine(c); } } } Output a b c d e....
Variable names. In isolated, small loops, a simple name such as the famous "i" is a good choice. It is standard. It is short. It is easy to type and remember.
But: If the variable is used to access an array, you can change the name to a more descriptive word to indicate its purpose.
Letter i: This identifier has no importance. It is simply a tradition. The book Code Complete by Steve McConnell has great detail here.
A name mistake. Single-letter loop iteration variables seem convenient. But what happens when we have nested loops, and mistake "i" for "j?" Sometimes more descriptive names are better.
Compilers. Programs commonly spend most of their time in tight loops such as for-loops. Compilers put considerable effort into speeding up these constructs. This is worthwhile.
Note: Fields of mathematics such as linear algebra can be used to analyze data reuse and data dependence in for-loops.
Note 2: Compilers use techniques such as strength reduction to improve performance of affine expressions based on iteration variables.
Strings. All kinds of loops work with strings. But the for-loop is often preferable for its syntax and index variable. Testing chars directly is fastest.
Loop, String CharsLoop, String
Arrays, 2d arrays. Loop constructs can be used upon arrays and 2D arrays. With 1D arrays, the code is straightforward. But with 2D arrays, we must divide our indexes to correctly loop.
Loop, ArrayLoop, String ArrayLoop, 2D Array
Performance. The for-loop is often the fastest way to loop over a series of numbers. It does not require allocations. It is easy for the compiler to optimize.
Array: The JIT compiler can detect array accesses in a for-loop. It can determine the iteration variable will never be out-of-bounds.
Then: It can automatically removes array bounds checking. Because of this, the simplest for-loops are sometimes fastest.
Optimization. How can we make loops go faster? Shaving nanoseconds off a program's runtime should always be at the top of our priority list. We try code tuning loops.
1. Decrement: This applies only to loops with indexes, like for-loops or while-loops or more complex foreach-loops.
2. Jam: Jam is a popular food. But when we jam loops, we combine them to reduce iterations in them.
3. Unwind: Do we really need a loop at all? Why not just unwind the loop statements?
Break. This stops a loop. It can be used with any kind of loop—it may be more useful in "while" loops. No further iterations are processed.
Continue. This stops the current iteration of a loop—it is like a "goto" to the end of the current loop block. The loop does not terminate.
Goto. This transfers control to an offset. With goto we can go to enclosing, but not enclosed, blocks. Goto is often considered a poor choice in programs.
Empty. The empty statement counts as a loop body. It is a simple semicolon after nothing. This lets us create loops that have no statements.
Spaghetti code. Loops help improve code that is hard to follow due to its complex flow control (often called spaghetti code). Loops impart structure to code.
Summarizing for: this loop is powerful and easy to write. It is my loop of choice. It makes a C# program feel more like the old times when developers were writing C code.