Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære do-while Loop | Loops
C# Basics

book
do-while Loop

The do-while loop is similar to the while loop however it executes the specified code block first and then checks the condition hence it always executes the code block at least once even if the condition is false.

Following is the syntax of the do-while loop:

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


Let's consider the practical example:

cs

main

copy
using System;

namespace ConsoleApp
{
internal class Program
{
static void Main(string[] args)
{
do {
Console.WriteLine("Hello World");
} while(1 < 0);
}
}
}
1234567891011121314
using System; namespace ConsoleApp { internal class Program { static void Main(string[] args) { do { Console.WriteLine("Hello World"); } while(1 < 0); } } }

The above code outputs "Hello World" even though the condition 1 < 0 is false. This will become more clear by looking at the flow diagram of the do-while loop:

question mark

How many iterations will the following loop have?

do {
Console.WriteLine("Hello World");
} while (false);

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 4. Kapittel 4

Spør AI

expand
ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt