-
C# Loops
-
In programming, one of the most common requirements is to repeat a block of code multiple times. Instead of writing the same code again and again, C# provides loops that allow you to execute a block of code repeatedly based on a condition.
Loops are a fundamental concept in C# and are widely used in real-world applications like data processing, validations, file handling, and much more.
What are Loops in C#?
Loops in C# are used to execute a block of code repeatedly until a specific condition is met.
They help reduce code duplication, improve readability, and make programs more efficient.
C# provides four main types of loops:
- for loop
- while loop
- do-while loop
- foreach loop
Why Loops Are Important
Let’s understand this with a simple example.
If you want to print numbers from 1 to 10 without loops:
Console.WriteLine(1); Console.WriteLine(2); Console.WriteLine(3); ...
This is inefficient and not scalable.
Using loops:
for (int i = 1; i <= 10; i++) { Console.WriteLine(i); }
This is clean, scalable, and efficient.
for Loop in C#
The for loop is used when you know in advance how many times you want to execute a block of code.
Syntax
for (initialization; condition; increment/decrement) { // Code to execute }How for Loop Works
- Initialization runs once
- Condition is checked before each iteration
- Loop executes if condition is true
- Increment/decrement updates the variable
Example
for (int i = 1; i <= 5; i++) { Console.WriteLine(i); }
Output
1 2 3 4 5Real-World Use Case
Use for loop when:
- You know the number of iterations
- You are working with arrays using index
- You need precise control over iteration
Nested for Loop
A nested loop is a loop inside another loop.
Example: Right Triangle Pattern using for Loop
Let’s print a simple right triangle pattern using nested for loops.
for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { Console.Write("* "); } Console.WriteLine(); }
Output
* * * * * * * * * * * * * * *How This Works
- The outer loop (
i) controls the number of rows - The inner loop (
j) controls how many stars are printed in each row - For each row, the number of stars increases based on
i
So:
- Row 1 → 1 star
- Row 2 → 2 stars
- Row 3 → 3 stars
- And so on...
Key Learning
- Nested loops are used for pattern problems
- Outer loop → rows
- Inner loop → columns (pattern elements)
Nested loops are useful for matrix operations, patterns, and grids.
while Loop in C#
The while loop is used when the number of iterations is not known beforehand.
Syntax
while (condition) { // Code }Example
int i = 1; while (i <= 5) { Console.WriteLine(i); i++; }
Real-World Use Case
- Reading user input until valid
- Waiting for a condition
- Unknown number of iterations
do-while Loop in C#
The do-while loop ensures that the code runs at least once.
Syntax
do { // Code } while (condition);
Example
int i = 6; do { Console.WriteLine(i); i++; } while (i <= 5);
Output
6Even though condition is false, loop runs once.
When to Use
- Menu-driven programs
- Input validation
- Execute at least once scenarios
foreach Loop in C#
The foreach loop is used to iterate over collections like arrays and lists.
Syntax
foreach (datatype variable in collection) { // Code }
Example
int[] numbers = { 1, 2, 3 }; foreach (int num in numbers) { Console.WriteLine(num); }
Why Use foreach
- No index handling
- Cleaner code
- Safer (no out-of-bounds error)
for vs while vs foreach (Quick Comparison)
Loop Use Case for Known iterations while Unknown iterations do-while At least one execution foreach Collections
Real-World Scenarios Using Each Loop Type
Understanding syntax is important, but knowing when to use each loop in real applications is what makes you a better developer.
Let’s explore practical scenarios where each loop type fits perfectly.
Using for Loop (Fixed Iterations)
Scenario: You need to apply a discount to 5 products.
double[] prices = { 100, 200, 300, 400, 500 }; for (int i = 0; i < prices.Length; i++) { prices[i] = prices[i] * 0.9; // Apply 10% discount Console.WriteLine(prices[i]); }
Why for loop?
- You know the number of items
- You need index access
Using while Loop (Unknown Iterations)
Scenario: Keep asking user input until valid number is entered.
string input; while (true) { Console.WriteLine("Enter a number:"); input = Console.ReadLine(); if (int.TryParse(input, out int result)) { Console.WriteLine("Valid input"); break; } }
Why while loop?
- Number of attempts is unknown
- Loop depends on condition
Using do-while Loop (At Least Once Execution)
Scenario: Display menu at least once.
int choice; do { Console.WriteLine("1. Add"); Console.WriteLine("2. Exit"); choice = Convert.ToInt32(Console.ReadLine()); } while (choice != 2);
Why do-while loop?
- Menu must show at least once
- Condition checked after execution
Using foreach Loop (Collections)
Scenario: Display list of users.
string[] users = { "Amit", "Rahul", "Neha" }; foreach (string user in users) { Console.WriteLine(user); }
Why foreach loop?
- No need for index
- Cleaner and safer iteration
Key Takeaway
- for → When count is known
- while → When condition-based looping
- do-while → When at least one execution is required
- foreach → When working with collections
Choosing the right loop improves code readability, performance, and maintainability.
Common Mistakes Developers Make
- Infinite loops
- Wrong loop condition
- Using foreach when index is needed
- Not updating loop variable
Best Practices
- Use for loop when count is known
- Use foreach for collections
- Avoid deep nested loops
- Keep conditions simple
Summary
Loops in C# are essential for executing repetitive tasks efficiently.
Each loop type serves a specific purpose, and choosing the right loop improves performance and readability.
Mastering loops helps you write clean and optimized code for real-world applications.