do while loop in C#

By   Calendar icon Apr 27, 2019   Level 1 icon

Description:

In this article, we explain how the do ... while statement in the C# language works and we give several examples.

Preferencesoft

Image by Misam Rizvi from Pixabay

do while loop

do ? while is a loop statement that can be used to repeat a statement or sequence of statements until a Boolean condition becomes false.

do statement; while (condition);

or

do
{
   statement_1;
   // ...
   statement_n;
}
while (condition);

Note: this statement is different from while loop since the condition is evaluated after the instruction block is executed.

Also, in this statement do ? while the instructions of the block are always executed at least once.

Example

Write a program that repetitively requests an integer to the user until it is > 0.

using System;
namespace dowhileloop
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        int n=0;
        do
        {
            System.Console.Write("Enter an integer n>0 ");
            n=int.Parse(Console.ReadLine());
            if (n<=0)
                System.Console.WriteLine("The integer is not suitable, please try again");
        }
        while (n<=0);
        System.Console.WriteLine("n={0}",n);
        System.Console.ReadKey();
    }
}
}

Output

Enter an integer n>0 -1
The integer is not suitable, please try again
Enter an integer n>0 -7
The integer is not suitable, please try again
Enter an integer n>0 8
n=8

Example

Write a program that repetitively requests a real number, displays its square and asks the user:

Do you want to continue (o/n)?

and that stops when the user enters a different data from o and O.

using System;
using System.Collections.Generic;
namespace dowhileloop
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        string ans  = "";
        do
        {
            System.Console.Write("Enter a real number x ");
            double d = double.Parse(Console.ReadLine());
            System.Console.WriteLine("x^2={0}",d*d);
            System.Console.Write("Do you want to continue (o/n)? ");
            ans = System.Console.ReadLine();
        }
        while (ans == "o" || ans == "O");
    }
}
}

Output

Enter a real number x 2
x^2=4
Do you want to continue (o/n)? o
Enter a real number x 1,5
x^2=2,25
Do you want to continue (o/n)? O
Enter a real number x -4e10
x^2=1,6E+21
Do you want to continue (o/n)? o
Enter a real number x -3,14
x^2=9,8596
Do you want to continue (o/n)? X

Example

Write a program asking the user for a list of integers and stopping the entry as soon as the user presses enter without any integer.

using System;
using System.Collections.Generic;
namespace dowhileloop
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        List<int> il = new List<int>();
        System.Console.WriteLine("Enter integers (Enter to stop) ");
        bool isInteger = true;
        do
        {
            System.Console.Write("? ");
            string ans =Console.ReadLine();
            if (ans == "") isInteger = false;
            else
            {
                int i;
                isInteger = int.TryParse(ans, out i);
                if (isInteger) il.Add(i);
                else
                {
                    System.Console.WriteLine("Not an integer! ");
                    isInteger = true; // to continue
                }
            }
        }
        while (isInteger);
        foreach (int n in il)
            System.Console.Write(" {0}", n);
    }
}
}

Output

Enter integers (Enter to stop)
? 45
? -4
? -789
? 20
?
45 -4 -789 20

Example

Let's write a program that generates random numbers between -5000 and 5000 until the last number generated is greater than the previous one (from the second number)

using System;
using System.Collections.Generic;
namespace dowhileloop
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        Random rand = new Random();
        int second  = rand.Next(-5001, 5001);
        System.Console.WriteLine("{0} ", second);
        int first;
        do
        {
            first = second;
            second  = rand.Next(-5001, 5001);
            System.Console.WriteLine("{0} ", second);
        }
        while (first <= second);
    }
}
}

Output

-3471
-1171
3098
1845

Example

Let's write a program that declares an array of different words and asks the user for a word (without space) until the returned string is part of the array. In addition, we will stop the loop if the user exceeds 10 tests.

using System;
using System.Collections.Generic;
namespace dowhileloop
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        int count = 0;
        int pos = 0;
        string[] words  = new string[] {"abc", "def", "ghi"};
        System.Console.WriteLine("To stop enter abc or def or ghi ");
        do
        {
            ++count;
            System.Console.Write("? ");
            string ans = Console.ReadLine();
            pos = Array.IndexOf(words, ans);
        }
        while (pos < 0 && count < 10);
    }
}
}

Output

To stop enter abc or def or ghi
? jjjjjjjj
? ...++
? 7878
? def

while or do ... while

Note: because the block statements are executed before the condition is evaluated, they cannot take into account the Boolean value of the condition, at least at the first pass in the loop.

Infinite do ? while loop

A do ? while loop is infinite when the condition in while remains true and its body contains no instruction causing a loop exit as break.

Example

using System;
using System.Collections.Generic;
namespace dowhileloop
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        do
            System.Console.Write("HELLO ");
        while (true);
    }
}
}

Empty do ? while loop

The only way to have a do while loop executing no instruction is to leave the instruction block empty between do and while.

Example

using System;
using System.Collections.Generic;
namespace dowhileloop
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        do
        {
        }
        while (DateTime.Now.Second < 20);
    }
}
}

Output

The program does not display anything! But it comes out of the loop when the sweep second hand of the clock is between 20 and 60.

Nested do ? while loops

do ? while loops are said to be nested If one of the loops is part of the instruction block of the other loop.

Example

Let's write a program that repeatedly asks the user for an integer number until the integer is ? 0 and that for each integer, displays on a line all positive multiple of 5 less than or equal to it.

using System;
using System.Collections.Generic;
namespace dowhileloop
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        int n = 0;
        do
        {
            System.Console.Write("Enter an integer n ");
            n = int.Parse(Console.ReadLine());
            int i=1;
            int m=5*i;
            if (m<=n)
                do
                {
                    System.Console.Write("{0} ",m);
                    ++i;
                    m=5*i;
                }
                while (m<=n);
            System.Console.WriteLine();
        }
        while (n>0);
    }
}
}

Output

Enter an integer n 1

Enter an integer n 4

Enter an integer n 5
5
Enter an integer n 25
5 10 15 20 25
Enter an integer n 44
5 10 15 20 25 30 35 40
Enter an integer n -1

Example

Let's write a program that asks for an integer n as long as it is positive and then writes n strings:

Item[1]

?

Item[n]

using System;
using System.Collections.Generic;
namespace dowhileloop
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        int n=0;
        do
        {
            System.Console.Write("Enter an integer n>0 ");
            n = int.Parse(Console.ReadLine());
            if (n>0)
            {
                int i=1;
                do
                    System.Console.WriteLine("item[{0}]",i++);
                while (i<=n);
            }
        }
        while (n>0);
    }
}
}

Output

Enter an integer n>0 5
item[1]
item[2]
item[3]
item[4]
item[5]
Enter an integer n>0 3
item[1]
item[2]
item[3]
Enter an integer n>0 1
item[1]
Enter an integer n>0 0

CSharp

Categories