
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, andforeachloops.Control repetition in your code.
Build small repetitive tasks like number counters and tables.
