Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Do while loop: Difference between revisions

From Coderwiki
new: info, example, while
 
m replace 'String' with 'string' in code example
 
Line 5: Line 5:
== Example ==
== Example ==
The following [[C Sharp]] code will loop until the [[User input|user enters]] 'stop', '''but the [[condition]] is only checked after the code block has first executed'''. This means that, even though it seems like the loop should stop right away as the [[condition]] is [[Boolean|false]], it still runs once (then the [[value]] is [[Assignment|overwritten]] anyway):<syntaxhighlight lang="cs" line="1">
The following [[C Sharp]] code will loop until the [[User input|user enters]] 'stop', '''but the [[condition]] is only checked after the code block has first executed'''. This means that, even though it seems like the loop should stop right away as the [[condition]] is [[Boolean|false]], it still runs once (then the [[value]] is [[Assignment|overwritten]] anyway):<syntaxhighlight lang="cs" line="1">
String input = "stop";
string input = "stop";
do {
do {
     input = Console.ReadLine();
     input = Console.ReadLine();

Latest revision as of 11:13, 15 August 2025

A do while loop will repeat (iterate) a code block while a condition is true, but will first check the condition after first running the codeblock.

This type of loop is known as indefinite iteration.

The following C Sharp code will loop until the user enters 'stop', but the condition is only checked after the code block has first executed. This means that, even though it seems like the loop should stop right away as the condition is false, it still runs once (then the value is overwritten anyway):

string input = "stop";
do {
    input = Console.ReadLine();
} while (input != "stop")

If you do not want the code to run at least once before checking the condition but instead want to check the condition first, you can use a while loop.

See: While loop