6

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

 3 years ago
source link: https://dev.to/gweaths/c-loops-part-3-do-while-and-while-loops-1idn
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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 modeExit 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 modeExit 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 modeExit 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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK