Do-While Loop

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 the block as long as a specified condition remains true. This differs from the while loop, which checks the condition before executing the block of code, meaning the block may not execute at all if the condition is initially false.

Structure of a do-while Loop

The basic structure of a do-while loop includes:

  • The do keyword followed by a block of code enclosed in curly braces {}.
  • The while keyword followed by a condition in parentheses () and a semicolon ;.

Here is the syntax for a do-while loop in C#

do
{
    // Code to be executed
} while (condition);

Example

using System;

class Program
{
    static void Main()
    {
        int number;
       
        do
        {
            Console.Write(“Enter a positive number: “);
            number = Convert.ToInt32(Console.ReadLine());

            if (number <= 0)
            {
                Console.WriteLine(“That is not a positive number. Please try again.”);
            }
        } while (number <= 0);
       
        Console.WriteLine($”You entered: {number});
    }
}

Explanation of the Example

  1. Initialization: An integer variable number is declared to store the user’s input.
  2. Loop Start: The do block is executed first, regardless of the condition.
  3. User Input: Inside the do block, the user is prompted to enter a positive number. The input is read and converted to an integer using Convert.ToInt32.
  4. Validation: The input is checked to see if it is a positive number. If not, an error message is displayed, and the loop iterates again.
  5. Condition Check: The condition while (number <= 0) is evaluated after the block of code has executed. If the condition is true (i.e., the number is not positive), the loop repeats. If false, the loop exits.
  6. Completion: Once a positive number is entered, the loop exits and the program prints the valid number.

Use Cases for do-while Loops

  1. User Input Validation: Ensuring the user provides valid input by repeating the prompt until the input meets the criteria.
  2. Menus and Repeatable Actions: Creating menus that allow users to choose actions, then repeating the menu until they select an exit option.
  3. Initial Setup Tasks: Performing tasks that need to be executed at least once before checking a condition to possibly repeat them.

Nested do-while Loops

do-while loops can also be nested within each other to handle more complex scenarios. For instance, consider a program that prompts the user to enter a matrix of positive numbers, validating each number:
using System;

class Program
{
    static void Main()
    {
        int rows = 2;
        int columns = 2;
        int[,] matrix = new int[rows, columns];

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                do
                {
                    Console.Write($”Enter a positive number for matrix[{i},{j}]: );
                    matrix[i, j] = Convert.ToInt32(Console.ReadLine());

                    if (matrix[i, j] <= 0)
                    {
                        Console.WriteLine(“That is not a positive number. Please try again.”);
                    }
                } while (matrix[i, j] <= 0);
            }
        }

        Console.WriteLine(“Matrix entered:”);
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                Console.Write(matrix[i, j] + ” “);
            }
            Console.WriteLine();
        }
    }
}

Explanation of the Nested Example

  1. Matrix Dimensions: Define the dimensions of the matrix.
  2. Outer Loop: Iterates over the rows of the matrix.
  3. Inner Loop: Iterates over the columns of the matrix.
  4. Nested do-while Loop: Ensures each element of the matrix is a positive number, prompting the user until valid input is received.
  5. Matrix Display: After all elements are entered, the matrix is displayed.
Post a comment

Leave a Comment

Scroll to Top