DEV Community

loading...

C# Loops - Part 3: Do..While and While Loops

Grant
senior .net web developer, with interests in tech, android and learning new technologies.
・1 min read

Do...While loops

Do while loops allow developers to repeat code execution as long as a condition is met. So whereas before we were instructing the code to run a number of times, or from beginning to end of an object. Now, we tailor it a little more and say only keep running this code "until" this condition is no longer valid.

How do they work then ?

do{
   //Code goes here
}
while(condition)
Enter fullscreen mode Exit fullscreen mode

Unlike the For and Foreach loop, the code is executed a minimum time of once. As the do code is ran before the while check.

Example :


var counter =0;

do {
   Console.WriteLine("Keep Going");
   counter++;
}
while (counter < 10);
Enter fullscreen mode Exit fullscreen mode

Here the code will run once, check if counter is less than 10, if it is it will keep going. Once the counter is >=10 the loop will exit and no longer execute the do code.

While Loop

Ok so the while loop works on a very similar concept to the do while, however rather than running the code first then checking. The check is done first. Meaning the code will only run whilst the condition is met.

Syntax and Example:

var sum = 0;
var dartsThrown = 0;
while(sum < 180 && dartsThrown <3)
{
  var dartScore = new Random.Next(61);
  sum+= dartScore;
}
Console.WriteLine("Your score is " + sum);
Enter fullscreen mode Exit fullscreen mode

Summary

There you go you've been introduced to the 4 ways of looping within C#. Each has there uses and are suited better for certain situations.

After you've played around with them yourself , you'll see how easy they are to use, and which loop would suit your needs best.

Discussion (0)