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.