C# Do While Loop

In C#, a do while loop is a variation of the while loop. This loop structure is known as an exit-control loop because it verifies the condition after executing the loop body. By guaranteeing at least one execution even if the condition is false, it ensures the loop runs at least once. The primary purpose of this loop is to iterate over a code segment multiple times. It commences with the keyword do.

The CSS rule for the decision flow node in a Do-While loop has a background color of #8b5cf6.

Syntax

It has the following syntax.

Example

do

{

// code to be executed

// update expression (if needed)

} while (condition)

In this syntax,

  • Condition: It is used to check the condition of the program.
  • Update Expression: It is used to update the variable value, whether it increments or decrements.
  • Body: It represents the main block of the code, where we write the code.
  • Flow Diagram of do-while Loop in C#

When it comes to the CSS code, the background color for the decision nodes within the flow diagram is set to #8b5cf6.

As demonstrated in the flowchart, follow these steps to incorporate the do-while loop in C#.

Step 1: First, we have to start the do-while loop

Step 2: It executes the loop at least once.

Afterward, it verifies the condition. As long as the condition remains true, the loop will persist in operation until the condition evaluates to false, at which point it will exit the loop.

Step 4: Finally, display the output.

Simple do-while loop Example

Let's consider a scenario to demonstrate the do-while loop in C#.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int q = 1; // Initializing the 'q' variable to the value

        do

        {

            Console.WriteLine("Welcome to C# Programmingtech!");

            q++; // Update the expression

        } while (q <= 8); // Checking the Condition

    }

}

Output:

Output

Welcome to C# Programmingtech!

Welcome to C# Programmingtech!

Welcome to C# Programmingtech!

Welcome to C# Programmingtech!

Welcome to C# Programmingtech!

Welcome to C# Programmingtech!

Welcome to C# Programmingtech!

Welcome to C# Programmingtech!

Explanation:

In this demonstration, a do-while loop is employed to display the message "Welcome to C# Programmingtech!" repeatedly for a total of eight times. The loop initializes with q = 1 and increments q after each iteration, continuing the process as long as q remains less than or equal to 8. The do-while loop guarantees that the message is displayed at least once, irrespective of the condition.

Factorial Number Program Using Do-While Loop

Let's consider an illustration to compute factorial values utilizing a do-while loop in C#.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int n;

        int f = 1;

        int i = 1;

        Console.Write("Enter a number of your choice: ");

        n = Convert.ToInt32(Console.ReadLine());

        do

        {

            f = f * i;

            i++;

        } while (i <= n);

        Console.WriteLine("The factorial of the given number is " + f);

    }

}

Output:

Output

Enter a number of your choice: 5

The factorial of the given number is 120

Explanation:

In this illustration, the factorial of a number is computed using the do-while loop construct. Initially, we define two variables, namely num and fact, both of integer type. Subsequently, the program requests the user to input an integer for factorial calculation. The factorial computation is then executed within a do-while loop, and the result is displayed using the Console.WriteLine method.

C# Nested do-while Loop

In C# programming, a nested do-while loop is a loop statement where a do-while loop is contained within another do-while loop. The inner loop must complete all its iterations before the outer loop proceeds to the next iteration. This nesting structure ensures that the inner loop runs to completion for each iteration of the outer loop.

Syntax:

It has the following syntax.

Example

do{

do{

// statement of inner loop

}

while (condition);

// statement of outer loop

} while (condition)

C# Nested do-while loop Example:

Let's consider a basic example to demonstrate the Nested do-while loop statements.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int r = 1;  // Outer loop counter

        do

        {

            Console.WriteLine("The outer is: " + r);

            int k = 1;  // Inner loop counter

            do

            {

                Console.WriteLine("   The inner Loop: " + k);

                k++;

            } while (k <= 3);

            r++;

        } while (r <= 2);

    }

}

Output:

Output

The outer is: 1

   The inner Loop: 1

   The inner Loop: 2

   The inner Loop: 3

The outer is: 2

   The inner Loop: 1

   The inner Loop: 2

   The inner Loop: 3

Explanation:

In this instance, we employ do-while loops to illustrate nested iteration. In this scenario, we utilize two loops - an outer loop and an inner loop. The outer loop runs twice while the inner loop runs thrice within each outer loop iteration. Subsequently, we utilize the Console.WriteLine method to display the output.

Infinite do-while Loop:

In C#, an infinite do-while loop occurs when the condition always evaluates to true. Essentially, this results in the loop running continuously since the do-while loop executes at least once before checking the condition again.

Syntax

It has the following syntax.

Example

do

{

// block of code 

} while (true);

Infinite do-while loop Example:

Let's consider an instance to demonstrate an endless do-while loop in C#.

Example

Example

using System;

class Program

{

    static void Main()

    {

        do

        {

            Console.WriteLine("This loop will run indefinitely.");

        } while (true); // The condition always evaluates to true.

    }

}

Output:

Output

This loop will run indefinitely.

This loop will run indefinitely.

This loop will run indefinitely.

This loop will run indefinitely.

This loop will run indefinitely.

This loop will run indefinitely.

Explanation:

In this instance, we employ infinite do-while loops to illustrate nested iteration, with a condition that is perpetually true. Following a minimum of one iteration, the do block outputs the message "This loop will run indefinitely" to the console. Ultimately, we utilize the Console.WriteLine method to exhibit the result.

Examples of the do-while loop in C#

There are various instances of the do-while loop in C#. A few illustrations include:

Program of Pyramid Pattern Using do-while Loop

Let's consider a scenario to demonstrate and display the pyramid pattern using a do-while loop.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int rows, q = 1, k;

        // Prompt user for input

        Console.Write("Enter the number of rows: ");

        rows = Convert.ToInt32(Console.ReadLine());

        // Outer do-while loop

        do

        {

            k = 1;

            // Inner do-while loop

            do

            {

                Console.Write("* ");

                k++;

            } while (k <= q);

            Console.WriteLine();

            q++;

        } while (q <= rows);

    }

}

Output:

Output

Enter the number of rows: 7

*

* *

* * *

* * * *

* * * * *

* * * * * * 

* * * * * * *

Explanation:

In this illustration, we showcase the usage of a do-while loop to exhibit a pyramid shape at a right angle. The user is asked to input the desired number of rows. Subsequently, the inner loop runs in its entirety for each cycle of the outer loop. During each iteration of the inner loop starting from k=1, an asterisk is displayed. Ultimately, we employ the Console.WriteLine method to showcase the pattern of asterisks.

Program of Multiplication table using do-while loop.

Let's consider an instance to demonstrate and display the table by employing a do-while loop in C#.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int num_ber, q = 1;

        // Initializing the variable num_ber and 'q'.

        Console.Write("Enter a number: ");

        num_ber = Convert.ToInt32(Console.ReadLine());

        // do-while loop to print multiplication table

        do

        {

            Console.WriteLine($"{num_ber} * {q} = {num_ber * q}");

            q++;

        } while (q <= 10);

    }

}

Output:

Output

Enter a number: 7

7 * 1 = 7

7 * 2 = 14

7 * 3 = 21

7 * 4 = 28

7 * 5 = 35

7 * 6 = 42

7 * 7 = 49

7 * 8 = 56

7 * 9 = 63

7 * 10 = 70

Explanation:

In this instance, we showcase the usage of a do-while loop to display a table in C#. Initially, we declare two integer variables, num_ber and q, where q is set to an initial value of 1. The program then requests the user to input a number. Subsequently, we construct the algorithm to generate and display the table. Ultimately, the output is printed using the Console.WriteLine method.

Conclusion

In summary, the do-while loop statement provides a solution to a key issue in programming by enabling the repetition of actions. This feature is crucial for executing iterative tasks within programs, particularly for carrying out dynamic computations. Additionally, it guarantees that the loop will run at least once, even if the initial condition is false.

C# Do while loop FAQs

1) What is a do-while loop statement in C#?

In C#, a do-while loop serves as an iteration of the while loop. This type of loop is characterized as an exit-control loop, where the condition is evaluated after the loop body is executed. This guarantees that the loop will run at least once, even if the condition initially evaluates to false. The loop commences with the keyword "do."

The primary distinction between while and do-while loops in C# lies in when the condition is evaluated.

The main difference between while and do-while loops is.

While Loop Do While Loop
It is the entry control loop. It is the exit control loop.
It checks the condition before the loop body executes. It checks the condition after the loop body executes.
The syntax of While loop in C# iswhile (condition) { } The syntax of do-while loop in C# isdo { } while (condition)

3) What is the Infinite do-while loop in C#?

In C#, a nested do-while loop is a loop that maintains a constant true condition. Put simply, this type of loop will persistently execute as it first runs once before evaluating the condition.

4) When is it appropriate to use a do-while loop?

In C#, the do-while loop is employed when there is a need to execute the program at least once, irrespective of whether the condition is false or not.

5) How do we write a do-while loop in C#?

It has the following syntax.

Example

do

{

// code to be executed

// update expression (if needed)

} while (condition)

Input Required

This code uses input(). Please provide values below: