- For Loop
- Foreach Loop
- While Loop
- Do -while Loop
1. For Loop
The for
loop is used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and iteration.
Syntax:
csharp1for (initialization; condition; iteration) 2{ 3 // Code to execute 4}
Example:
csharp1for (int i = 0; i < 5; i++) 2{ 3 Console.WriteLine("Iteration: " + i); 4}
Output:
1Iteration: 0 2Iteration: 1 3Iteration: 2 4Iteration: 3 5Iteration: 4
2. Foreach Loop
The foreach
loop is specifically designed for iterating over collections, such as arrays, lists, or any object that implements the IEnumerable
interface. It simplifies the syntax and reduces the risk of errors.
Syntax:
csharp1foreach (var item in collection) 2{ 3 // Code to execute 4}
Example:
csharp1string[] fruits = { "Apple", "Banana", "Cherry" }; 2 3foreach (var fruit in fruits) 4{ 5 Console.WriteLine(fruit); 6}
Output:
1Apple 2Banana 3Cherry
3. While Loop
The while
loop continues to execute as long as the specified condition is true. The condition is checked before the loop's body is executed.
Syntax:
csharp1while (condition) 2{ 3 // Code to execute 4}
Example:
csharp1int count = 0; 2 3while (count < 5) 4{ 5 Console.WriteLine("Count: " + count); 6 count++; 7}
Output:
1Count: 0 2Count: 1 3Count: 2 4Count: 3 5Count: 4
4. Do-While Loop
The do-while
loop is similar to the while
loop, but it guarantees that the loop's body will be executed at least once, as the condition is checked after the execution of the loop body.
Syntax:
csharp1do 2{ 3 // Code to execute 4} while (condition);
Example:
csharp1int count = 0; 2 3do 4{ 5 Console.WriteLine("Count: " + count); 6 count++; 7} while (count < 5);
Output:
1Count: 0 2Count: 1 3Count: 2 4Count: 3 5Count: 4
5. Breaking and Continuing Loops
- Break Statement: The
break
statement is used to exit a loop prematurely. It can be used in any loop.
Example:
csharp1for (int i = 0; i < 10; i++) 2{ 3 if (i == 5) 4 { 5 break; // Exit the loop when i is 5 6 } 7 Console.WriteLine(i); 8}
Output:
10 21 32 43 54
- Continue Statement: The
continue
statement skips the current iteration and moves to the next iteration of the loop.
Example:
csharp1for (int i = 0; i < 10; i++) 2{ 3 if (i % 2 == 0) 4 { 5 continue; // Skip even numbers 6 } 7 Console.WriteLine(i); 8}
Output:
11 23 35 47 59
Summary
- For Loop: Ideal when the number of iterations is known.
- Foreach Loop: Simplifies iteration over collections.
- While Loop: Executes as long as a condition is true, with the condition checked before the loop body.
- Do-While Loop: Executes at least once, with the condition checked after the loop body.
- Break Statement: Exits the loop immediately.
- Continue Statement: Skips the current iteration and proceeds to the next.