Skip to content

Repeat with do while

You can also repeat code using a do while loop. This works like the while loop, but the condition appears after the loop’s instructions. This means that you have to run these instructions at least once.

Illustration of a do while loop

Example

The following example shows a menu in the terminal. This is one place where a do while loop can work well.

using static SplashKitSDK.SplashKit;
using static System.Convert;
string line;
do
{
WriteLine("1: Say hello");
WriteLine("2: ...");
WriteLine("3: Quit");
line = ReadLine();
switch(line)
{
case "1":
WriteLine("Hello!");
break;
case "2":
WriteLine("...");
break;
case "3":
break;
default:
WriteLine("Please enter a menu option");
break;
}
} while(line != "3");