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:
C# Example
In C#, the for loop is used similarly, but the syntax is slightly different. Here's a basic example:
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:
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 to1
. This is where you set up your loop variable.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 asi
is less than or equal to5
.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++
incrementsi
by1
after each loop iteration.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 ofi
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?