For loops

A for loop is a control flow statement for specifying iteration, which allows code to be executed repeatedly. The for loop is used when you know in advance how many times you want to execute a statement or a block of statements. It is commonly used for iterating over a sequence (such as a list, tuple, dictionary, set, or string) or other iterable objects.

The for loop has a standard structure which includes: initialization, condition, and increment/decrement statements. The loop initiates the iteration by setting an initial value for its counter. Then, before each iteration, it evaluates the condition. If the condition is true, the loop's body is executed. After the body of the for loop executes, the loop increments or decrements the counter. This process repeats until the condition becomes false.

Python Example

In Python, the for loop is used to iterate over the elements of a sequence (like a list, tuple, string) or other iterable objects. Here’s a simple example:

# Python example that prints numbers from 1 to 5
for i in range(1, 6):
    print(i)

C# Example

In C#, the for loop is used similarly, but the syntax is slightly different. Here's a basic example:

// C# example that prints numbers from 1 to 5
for (int i = 1; i <= 5; i++)
{
    Console.WriteLine(i);
}

Understanding the classic loop syntax

The C# for loop syntax is the "classic" syntax. Let's break down the syntax of the for loop as seen in the example:

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine(i);
}
  1. Initialization (int i = 1): This part is executed only once at the beginning of the loop. It allows us to declare and initialize the loop counter variable. In the example, i is initialized to 1. This is where you set up your loop variable.

  2. Condition (i <= 5): Before each iteration of the loop, C# evaluates this condition. If the condition evaluates to true, the loop body is executed. If it is false, the loop stops. In our example, the loop will continue as long as i is less than or equal to 5.

  3. Increment/Decrement (i++): After each iteration of the loop body, this part is executed. It's often used to increment or decrement the loop counter. In the example, i++ increments i by 1 after each loop iteration.

  4. Loop Body ({ Console.WriteLine(i); }): This is the block of code that gets executed repeatedly as long as the condition is true. Each time the condition evaluates to true, the code inside the loop body is executed. In the example, it prints the current value of i to the console.

Each of these components plays a vital role in how the for loop operates, providing a compact way to iterate over a range of values with precise control over the start point, end point, and the increment/decrement step size.

Last updated

Was this helpful?