c sharp Logo

C# For Loop


For Loops

The for loop is a control flow structure in C# used to execute a block of code repeatedly a fixed number of times. It is commonly used for iterating over a sequence of elements, such as arrays or collections.

Syntax

The syntax of a for loop is as follows:

for (initialization; condition; increment) {

  // Code block to execute repeatedly

}

 

Components of the For Loop

Initialization: This statement is executed only once at the beginning of the loop. It typically initializes a loop control variable.

Condition: This expression is evaluated before each iteration of the loop. If the condition is true, the loop body is executed. If the condition is false, the loop terminates.

Increment: This statement is executed after each iteration of the loop. It typically modifies the loop control variable to prepare for the next iteration.

Example

The following code prints the numbers from 1 to 10:

for (int number = 1; number <= 10; number++) {

  Console.WriteLine(number);

}

 

Benefits of Using For Loops

  • Clear and concise syntax for repetitive tasks.
  • Easy to understand and maintain.
  • Efficient for iterating over fixed-length sequences.

Conclusion

The for loop is a fundamental control flow structure in C# that enables efficient and structured iteration over sequences of elements. It is a versatile tool for various programming tasks, from simple numerical sequences to complex data processing.