The for Loop
The
for loop is used to repeat a block of code a specific number of times. It is especially useful when the number of iterations is known in advance or when you need to iterate over a collection.General syntax of the for loop
The
for loop consists of three main parts:- initialization - usually used to declare and initialize the loop counter.
- condition - checked before each iteration. If the condition is true, the loop body is executed. If false, the loop ends.
- iteration - executed after each iteration of the loop. Usually used to change the counter value.
Line 1, Char 1
Example of using the for loop
Line 1, Char 1
Description:
- Initialization:
int i = 0— variable i is declared and set to 0. - Condition:
i < 5— the loop continues while i is less than 5. - Iteration:
i++— increases the value of i by 1 after each iteration. - Loop body:
Console.WriteLine("Value of i: " + i);— prints the current value of i.
Iterating over array elements
The
for loop is often used to iterate over array elements Line 1, Char 1
Using the break operator
The
break operator completely stops the loop. It is useful when you need to finish the loop early. Line 1, Char 1
Using the continue operator
The
continue operator skips the rest of the current iteration and moves to the next one Line 1, Char 1
Exercises
- Print only even numbers that are less than 10. A number is even if the remainder when divided by 2 equals 0:
i % 2 == 0.
Line 1, Char 1
- Given the array
int[] numbers = new int[] { 1, 2, 3, -1, 4, 5 };. Print it, but if an element is less than 0, print an error message and stop the loop early.
Line 1, Char 1