CHASH Tutorial



C# LOOPS


C# Loops — for, while, do-while, foreach

Loops help you run the same block of code multiple times. Here are the main types in C#:

  • for — repeats code a set number of times
  • while — repeats while a condition is true
  • do-while — like while, but runs at least once
  • foreach — loops through items in a collection

1. for Loop

Use it when you know exactly how many times to run the loop.

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine("Count: " + i);
}
  

2. while Loop

Repeats as long as the condition is true. Condition checked before each run.

int i = 1;
while (i <= 5)
{
    Console.WriteLine("Count: " + i);
    i++;
}
  

3. do-while Loop

Runs the code once first, then repeats while condition is true.

int i = 1;
do
{
    Console.WriteLine("Count: " + i);
    i++;
} while (i <= 5);
  

4. foreach Loop

Loops through every item in a collection (like an array).

string[] fruits = { "Apple", "Banana", "Cherry" };

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}
  

Try It Yourself

Change the loop count and items, then click Run to see the output.




🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review