C# do-while Loop

Introduction

The do-while loop in C# is a control flow statement that allows you to execute a block of code at least once and then repeatedly execute it as long as a specified condition is true. Unlike the while loop, the do-while loop checks the condition after the loop body has executed, ensuring that the code block runs at least once.

Syntax

do
{
    // Code to execute at least once and repeatedly while the condition is true
} while (condition);

Components of a do-while Loop

  1. Loop Body: This section contains the code that will be executed at least once and then repeatedly as long as the condition is true.
  2. Condition: This section is evaluated after each iteration of the loop. If the condition is true, the loop body executes again. If the condition is false, the loop terminates.

Example

Here’s a complete example demonstrating the use of the do-while loop in C#:

using System;

namespace DoWhileLoopExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int counter = 1;

            // Using a do-while loop to print numbers from 1 to 10
            do
            {
                Console.WriteLine("Number: " + counter);
                counter++; // Increment the counter
            } while (counter <= 10);

            // This will always be executed
            Console.WriteLine("Program finished.");
        }
    }
}

Output

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
Number: 10
Program finished.

Explanation

  1. Initialization: int counter = 1; initializes the counter variable to 1.
  2. Loop Body: Console.WriteLine("Number: " + counter); prints the current value of the counter. counter++; increments the counter by 1.
  3. Condition: counter <= 10; checks if the counter is less than or equal to 10. If true, the loop body executes again. If false, the loop terminates.

Example: Summing Numbers with a do-while Loop

This example calculates the sum of numbers from 1 to 100 using a do-while loop:

using System;

namespace SumDoWhileLoopExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int sum = 0;
            int number = 1;

            // Using a do-while loop to calculate the sum of numbers from 1 to 100
            do
            {
                sum += number;
                number++;
            } while (number <= 100);

            Console.WriteLine("Sum of numbers from 1 to 100: " + sum);

            // This will always be executed
            Console.WriteLine("Program finished.");
        }
    }
}

Output

Sum of numbers from 1 to 100: 5050
Program finished.

Explanation

  1. Initialization: int sum = 0; int number = 1; initializes the sum and number variables.
  2. Loop Body: sum += number; adds the current value of the number to the sum. number++; increments the number by 1.
  3. Condition: number <= 100; checks if the number is less than or equal to 100. If true, the loop body executes again. If false, the loop terminates.

Example: Reading User Input

This example uses a do-while loop to read user input until the user enters "exit":

using System;

namespace ReadInputDoWhileLoop
{
    class Program
    {
        static void Main(string[] args)
        {
            string input;

            // Using a do-while loop to read user input until "exit" is entered
            do
            {
                Console.WriteLine("Enter a command (type 'exit' to quit):");
                input = Console.ReadLine();
                Console.WriteLine("You entered: " + input);
            } while (input.ToLower() != "exit");

            // This will always be executed
            Console.WriteLine("Program finished.");
        }
    }
}

Output

Enter a command (type 'exit' to quit):
hello
You entered: hello
Enter a command (type 'exit' to quit):
exit
You entered: exit
Program finished.

Explanation

  1. Initialization: string input; declares the input variable.
  2. Loop Body: Console.WriteLine("Enter a command (type 'exit' to quit):"); prompts the user for input. input = Console.ReadLine(); reads the user input. Console.WriteLine("You entered: " + input); prints the entered input.
  3. Condition: input.ToLower() != "exit"; checks if the input is not equal to "exit". If true, the loop body executes again. If false, the loop terminates.

Conclusion

The do-while loop is a useful control flow statement that ensures the loop body is executed at least once before checking the condition. It is particularly useful when you need to execute a block of code and then check if it should be repeated. By understanding and using the do-while loop, you can handle various repetitive tasks in your C# programs efficiently.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top