Day 4: Loops (for, while, foreach)
T
Tuan Beo

Day 4: Loops (for, while, foreach)

Learn how to repeat tasks automatically using loops to make your programs efficient.

πŸ“ Theory (Details)

Loops help you run the same block of code multiple times until a condition is met.

1️⃣ For Loop

Used when you know exactly how many times you want to repeat something.

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

2️⃣ While Loop

Used when you don’t know in advance how many times to loop β€” continues as long as a condition is true.

int number = 1;
while (number <= 5)
{
    Console.WriteLine($"Number: {number}");
    number++;
}

3️⃣ Do-While Loop

Executes at least once, even if the condition is false.

int x = 1;
do
{
    Console.WriteLine($"x = {x}");
    x++;
} while (x <= 5);

4️⃣ Foreach Loop

Best for looping through collections like arrays or lists.

string[] names = { "Alice", "Bob", "Charlie" };
foreach (string name in names)
{
    Console.WriteLine(name);
}

πŸ’» Practice

Step 1 – Print Numbers from 1 to 10

for (int i = 1; i <= 10; i++)
{
    Console.WriteLine(i);
}

Step 2 – While Loop Example

Ask the user for a number, then print all numbers up to that number.

Console.Write("Enter a number: ");
int n = Convert.ToInt32(Console.ReadLine());

int counter = 1;
while (counter <= n)
{
    Console.WriteLine(counter);
    counter++;
}

Step 3 – Foreach Example

Loop through a list of your favorite foods.

string[] foods = { "Pizza", "Sushi", "Pho" };
foreach (string food in foods)
{
    Console.WriteLine($"I love {food}");
}

Step 4 – Mini Exercise 🎯

Write a program that asks the user for a number and prints its multiplication table (1–10).
Example output for input 3:

3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
...
3 x 10 = 30

πŸ’‘ Hint: Use a for loop.


βœ… Checkpoint:
Now you can:

  • Use for, while, do-while, and foreach loops.

  • Control repetition in your code.

  • Build small repetitive tasks like number counters and tables.

Comments