While Loops in C#


A really common mistake in while loops is infinite loops, so it’s important to remember to increment i below console.WriteLine so that it doesn’t continue displaying 1 forever.

i += 1; is another way of writing  i++;


Problem Solving With While Loops


Here I’ve coded a While Loop for the number of attempts it takes to roll a six on a dice given that there is a one in six chance.

I defaulted the numberOfAttempts to 0 as no attempts had been made yet.

The int attempt stores the single attempt and as long as the number does not equal six, != 6 the code will loop the code setting the attempt to a new random value.

To generate random I referenced the random class, similarly to in a previous post.

I’ve set the parameters of attempt = numberGen.Next(1, 7); because the dice roll limits the numbers 1 to 6. Again 1 being inclusive and 7 being exclusive. This could also be written as (1, 6 + 1);

I also experimented with a do while loop, which required you to be sure the code would perform at least one iteration.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s