Loops: for, foreach, while and do-while

Dot NET Programming 13 min min read Updated: Nov 16, 2026 Beginner
Loops: for, foreach, while and do-while
Beginner Topic 4 of 9

Why Loops?

A loop repeats code. Without loops, printing the numbers 1 to 100 would take 100 lines.

for Loop: When You Know How Many Times

csharp for (int i = 1; i <= 5; i++) { Console.WriteLine($"Number {i}"); }
PartMeaning
int i = 1Start: runs once
i <= 5Condition: checked before each round
i++Step: runs after each round

foreach: Go Through Every Item

csharp string[] cities = { "Delhi", "Paris", "Tokyo" }; foreach (string city in cities) { Console.WriteLine(city); }
foreach is read-only: You cannot change the collection itself inside a foreach (for example add or remove items). Use a for loop when you need the index.

while: Repeat While a Condition is True

csharp int count = 3; while (count > 0) { Console.WriteLine(count); count--; } Console.WriteLine("Liftoff!");

do-while: Run At Least Once

csharp string? answer; do { Console.Write("Type 'yes' to continue: "); answer = Console.ReadLine(); } while (answer != "yes");

break and continue

csharp for (int i = 1; i <= 10; i++) { if (i == 3) continue; // skip 3 if (i == 6) break; // stop the loop at 6 Console.WriteLine(i); // 1 2 4 5 }

Nested Loops: A Multiplication Table

csharp for (int row = 1; row <= 3; row++) { for (int col = 1; col <= 3; col++) { Console.Write($"{row * col,4}"); } Console.WriteLine(); }
Result

Each row prints three numbers: 1 2 3, then 2 4 6, then 3 6 9, lined up in columns.

Common Patterns

csharp int[] numbers = { 4, 8, 15, 16, 23, 42 }; // sum int sum = 0; foreach (int n in numbers) sum += n; // maximum int max = numbers[0]; foreach (int n in numbers) if (n > max) max = n; // search bool found = false; foreach (int n in numbers) { if (n == 15) { found = true; break; } }
Infinite loops: If the condition never becomes false, the loop never ends. Make sure something inside the loop changes the condition. Press Ctrl + C in the terminal to stop it.
LoopUse when
forYou know the count or need the index
foreachYou want every item of a collection
whileYou repeat until something happens
do-whileYou must run the body at least once

Conclusion

Choose for for counting, foreach for collections, while for 'until' logic and use break and continue to control the flow.

Quick Summary: for = count, foreach = each item, while = until, do-while = at least once.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators