DEV Community

AllCoderThings
AllCoderThings

Posted on

C# Loops (for, foreach, while, do-while)

Originally published at https://allcoderthings.com/en/article/csharp-loops-for-foreach-while-do-while

In C#, loops allow us to execute the same block of code repeatedly as long as a certain condition is true. They save time for the programmer and make it easy to perform repetitive tasks. The most commonly used loops in C# are: for, foreach, while, and do-while.

for Loop

The for loop is generally used when the number of repetitions is known. It is controlled with a counter variable.

Counting Up: The i counter increases by 1 each time. The loop ends before it reaches 5.

for (int i = 0; i < 5; i++)
{
    Console.WriteLine("Step: " + i);
}
Enter fullscreen mode Exit fullscreen mode
// Output:
Step: 0
Step: 1
Step: 2
Step: 3
Step: 4
Enter fullscreen mode Exit fullscreen mode

Counting Down: The i counter decreases by 1 each time. The loop ends before it reaches 0.

for (int i = 5; i > 0; i--)
{
    Console.WriteLine("Countdown: " + i);
}
Enter fullscreen mode Exit fullscreen mode
// Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Enter fullscreen mode Exit fullscreen mode

Increment by 5: The i counter increases by 5 each time. The loop ends when it reaches 25.

for (int i = 0; i <= 25; i += 5)
{
    Console.WriteLine("Number: " + i);
}
Enter fullscreen mode Exit fullscreen mode
// Output:
Number: 0
Number: 5
Number: 10
Number: 15
Number: 20
Number: 25
Enter fullscreen mode Exit fullscreen mode

Nested for Loop: With nested i and j counters, each counting up to 3, the program prints their products.

for (int i = 1; i <= 3; i++)
{
    for (int j = 1; j <= 3; j++)
    {
        Console.Write($"{i * j}\t");
    }
    Console.WriteLine();
}
Enter fullscreen mode Exit fullscreen mode
// Output:
1    2    3
2    4    6
3    6    9
Enter fullscreen mode Exit fullscreen mode

break and continue

Sometimes in loops, the break and continue keywords are used to control the flow.

break: Completely terminates the loop.

for (int i = 1; i <= 5; i++)
{
    if (i == 3)
        break; // when i equals 3, the loop ends

    Console.WriteLine("i: " + i);
}
Enter fullscreen mode Exit fullscreen mode
// Output:
i: 1
i: 2
Enter fullscreen mode Exit fullscreen mode

continue: Skips only the current iteration and continues with the rest of the loop.

for (int i = 1; i <= 5; i++)
{
    if (i == 3)
        continue; // when i equals 3, this step is skipped

    Console.WriteLine("i: " + i);
}
Enter fullscreen mode Exit fullscreen mode
// Output:
i: 1
i: 2
i: 4
i: 5
Enter fullscreen mode Exit fullscreen mode

foreach Loop

The foreach loop is used to iterate over collections (array, list, etc.). You don’t need to know the number of elements.

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

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}
Enter fullscreen mode Exit fullscreen mode

while Loop

The while loop repeats as long as the condition is true. The number of iterations may not be known beforehand.

Simple Counter: The number variable starts at 1 and is printed up to 3.

int number = 1;

while (number <= 3)
{
    Console.WriteLine("Number: " + number);
    number++;
}
Enter fullscreen mode Exit fullscreen mode
// Output:
Number: 1
Number: 2
Number: 3
Enter fullscreen mode Exit fullscreen mode

Printing Characters of a String: In this example, a while loop prints each character of a text. If a space character is found, it is skipped with continue. If a period (.) is found, the loop ends with break.

string text = "The weather is nice. Let's go outside.";
int index = 0;

while (index < text.Length)
{
    char c = text[index];

    if (c == ' ')
    {
        index++;
        continue; // skip spaces
    }

    if (c == '.')
        break; // end loop when a period is found

    Console.WriteLine(c);
    index++;
}
Enter fullscreen mode Exit fullscreen mode
// Output:
T
h
e
w
e
a
t
h
e
r
i
s
n
i
c
e
Enter fullscreen mode Exit fullscreen mode

Infinite while(true) Example: In infinite loops, you can exit with break. In this example, the user is repeatedly asked for a password until the correct one is entered.

while (true)
{
    Console.Write("Enter password: ");
    string password = Console.ReadLine();

    if (password == "1234")
    {
        Console.WriteLine("Login successful!");
        break; // correct password entered, exit loop
    }

    Console.WriteLine("Incorrect password, try again.");
}
Enter fullscreen mode Exit fullscreen mode
// Example Run:
Enter password: 1111
Incorrect password, try again.
Enter password: 2222
Incorrect password, try again.
Enter password: 1234
Login successful!
Enter fullscreen mode Exit fullscreen mode

do-while Loop

The do-while loop runs at least once and then checks the condition. This means it executes once even if the condition is false.

Simple Example: Even if the condition is not satisfied initially, the loop runs once.

int x = 5;

do
{
    Console.WriteLine("x value: " + x);
    x++;
} while (x < 5);
Enter fullscreen mode Exit fullscreen mode
// Output:
x value: 5
Enter fullscreen mode Exit fullscreen mode

Finding Divisors: Using a do-while loop to find the divisors of a user-entered number.

Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());

if (number <= 0)
{
    Console.WriteLine("Enter a number greater than 0.");
}
else
{
    int divisor = number;

    Console.WriteLine($"Divisors of {number}:");

    do
    {
        if (number % divisor == 0)
        {
            Console.WriteLine(divisor);
        }
        divisor--;
    } while (divisor >= 1);
}
Enter fullscreen mode Exit fullscreen mode
// Example Run:
Enter a number: 12
Divisors of 12:
12
6
4
3
2
1
Enter fullscreen mode Exit fullscreen mode

Summary

  • for → Suitable for counter-controlled iterations.
  • foreach → Used to iterate over arrays or collections.
  • while → Repeats as long as the condition is true.
  • do-while → Runs at least once, then checks the condition.
  • break → Terminates the loop.
  • continue → Skips the current iteration of the loop.

Application: Menu and Product Management with Arrow Keys

In this example, we write a simple menu that works with an infinite loop and allows selection using the arrow keys (↑/↓) and Enter. Arrays are used to store the name and price information of 5 products. The menus are: Print Products, Update Product, Delete Product, Exit.

using System;
using System.Globalization;

class Program
{
    static void Main()
    {
        string[] productNames = { "Pen", "Notebook", "Eraser", "Bag", "Ruler" };
        decimal[] productPrices = { 12.5m, 45m, 7.9m, 350m, 22.75m };

        string[] menu = { "Print Products", "Update Product", "Delete Product", "Exit" };
        int selected = 0;

        while (true) // Infinite loop
        {
            Console.Clear();
            Console.WriteLine("=== Product Management ===\n");

            // Menu drawing
            for (int i = 0; i < menu.Length; i++)
            {
                if (i == selected)
                {
                    Console.ForegroundColor = ConsoleColor.Black;
                    Console.BackgroundColor = ConsoleColor.Cyan;
                    Console.WriteLine($"> {menu[i]}");
                    Console.ResetColor();
                }
                else
                {
                    Console.WriteLine($"  {menu[i]}");
                }
            }

            Console.WriteLine("\nUse arrow keys to navigate, Enter to select, Esc to quit.");

            var key = Console.ReadKey(true);

            if (key.Key == ConsoleKey.UpArrow)
                selected = (selected - 1 + menu.Length) % menu.Length;
            else if (key.Key == ConsoleKey.DownArrow)
                selected = (selected + 1) % menu.Length;
            else if (key.Key == ConsoleKey.Escape)
                break;
            else if (key.Key == ConsoleKey.Enter)
            {
                if (selected == 0) // Print Products
                {
                    Console.Clear();
                    Console.WriteLine("=== Product List ===\n");
                    for (int i = 0; i < productNames.Length; i++)
                    {
                        string name = string.IsNullOrWhiteSpace(productNames[i]) ? "(deleted)" : productNames[i];
                        Console.WriteLine($"{i + 1}. {name,-15} | {productPrices[i],8:0.00} USD");
                    }
                    Console.WriteLine("\nPress any key to continue...");
                    Console.ReadKey(true);
                }
                else if (selected == 1) // Update Product
                {
                    int index = 0;
                    while (true)
                    {
                        Console.Clear();
                        Console.WriteLine("=== Select a Product to Update ===\n");
                        for (int i = 0; i < productNames.Length; i++)
                        {
                            string name = string.IsNullOrWhiteSpace(productNames[i]) ? "(deleted)" : productNames[i];
                            if (i == index)
                            {
                                Console.ForegroundColor = ConsoleColor.Black;
                                Console.BackgroundColor = ConsoleColor.Yellow;
                                Console.WriteLine($"> {i + 1}. {name,-15} | {productPrices[i],8:0.00} USD");
                                Console.ResetColor();
                            }
                            else
                            {
                                Console.WriteLine($"  {i + 1}. {name,-15} | {productPrices[i],8:0.00} USD");
                            }
                        }
                        Console.WriteLine("\nUse arrow keys to navigate, Enter to select, Esc to go back.");
                        var k = Console.ReadKey(true);
                        if (k.Key == ConsoleKey.UpArrow) index = (index - 1 + productNames.Length) % productNames.Length;
                        else if (k.Key == ConsoleKey.DownArrow) index = (index + 1) % productNames.Length;
                        else if (k.Key == ConsoleKey.Escape) break;
                        else if (k.Key == ConsoleKey.Enter)
                        {
                            Console.Clear();
                            Console.WriteLine("=== Update Product ===\n");
                            Console.WriteLine($"Selected: {productNames[index]} | Old price: {productPrices[index]:0.00} USD\n");

                            Console.Write("New name (leave blank to keep): ");
                            string newName = Console.ReadLine();
                            if (!string.IsNullOrWhiteSpace(newName))
                                productNames[index] = newName.Trim();

                            Console.Write("New price (leave blank to keep): ");
                            string priceStr = Console.ReadLine();
                            if (decimal.TryParse(priceStr, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal newPrice))
                                productPrices[index] = Math.Max(0, newPrice);

                            Console.WriteLine("\nUpdate completed. Press any key to continue...");
                            Console.ReadKey(true);
                            break;
                        }
                    }
                }
                else if (selected == 2) // Delete Product
                {
                    int index = 0;
                    while (true)
                    {
                        Console.Clear();
                        Console.WriteLine("=== Select a Product to Delete ===\n");
                        for (int i = 0; i < productNames.Length; i++)
                        {
                            string name = string.IsNullOrWhiteSpace(productNames[i]) ? "(deleted)" : productNames[i];
                            if (i == index)
                            {
                                Console.ForegroundColor = ConsoleColor.Black;
                                Console.BackgroundColor = ConsoleColor.Red;
                                Console.WriteLine($"> {i + 1}. {name,-15} | {productPrices[i],8:0.00} USD");
                                Console.ResetColor();
                            }
                            else
                            {
                                Console.WriteLine($"  {i + 1}. {name,-15} | {productPrices[i],8:0.00} USD");
                            }
                        }
                        Console.WriteLine("\nUse arrow keys to navigate, Enter to select, Esc to go back.");
                        var k = Console.ReadKey(true);
                        if (k.Key == ConsoleKey.UpArrow) index = (index - 1 + productNames.Length) % productNames.Length;
                        else if (k.Key == ConsoleKey.DownArrow) index = (index + 1) % productNames.Length;
                        else if (k.Key == ConsoleKey.Escape) break;
                        else if (k.Key == ConsoleKey.Enter)
                        {
                            productNames[index] = string.Empty;
                            productPrices[index] = 0m;
                            Console.WriteLine("\nProduct deleted. Press any key to continue...");
                            Console.ReadKey(true);
                            break;
                        }
                    }
                }
                else if (selected == 3) // Exit
                {
                    return;
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Notes:

  • Navigation with arrow keys is handled using Console.ReadKey(true) and ConsoleKey.
  • Menus are redrawn inside an infinite loop; exit with Esc or Exit.
  • Deleted products are shown with the (deleted) label and a price of 0 USD.
  • decimal.TryParse is used for numeric conversion of price input.

Top comments (0)