Loops help you run the same block of code multiple times. Here are the main types in C#:
Use it when you know exactly how many times to run the loop.
for (int i = 1; i <= 5; i++) { Console.WriteLine("Count: " + i); }
Repeats as long as the condition is true. Condition checked before each run.
int i = 1; while (i <= 5) { Console.WriteLine("Count: " + i); i++; }
Runs the code once first, then repeats while condition is true.
int i = 1; do { Console.WriteLine("Count: " + i); i++; } while (i <= 5);
Loops through every item in a collection (like an array).
string[] fruits = { "Apple", "Banana", "Cherry" }; foreach (string fruit in fruits) { Console.WriteLine(fruit); }
Change the loop count and items, then click Run to see the output.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!