Chapter 6: Loops.
until now, all the programs we wrote performed an action and finished, but naturally, in a game we don't want that, instead, it should keep doing something until the user presses escape, alt f4, or something like that.
this is done through loops.
While loops.
the simplist form of loops are while loops.
While loops are exactly the same as an if condition, but the difference is that, the code inside the while block executes until the statement fails.
let's look at an example.
int x = 0;
while (x < 10)
{
Console.WriteLine(x);
x++;
}
exactly like an if condition, but the use is just different.
the loop above runs 10 times, because when it starts the first time, x is 0, then it increases the first time to become 1 until it reachs 9, it's 9 and not 10 because our condition is < 10, not <= 10
x++ increments x by one, so the first time x becomes 1, second 2, etc.
let's look at a practical example, let's say we modified our guess the number code
Random random = new();
int number = random.Next(1, 101);
while (true) // true for an infinite loop. Since the condition is always successful.
{
Console.WriteLine("Enter your guess between 1 and 100");
int guess = int.Parse(Console.ReadLine());
if (guess == number)
{
Console.WriteLine("Congratulations! You guessed right.");
break;
}
else if (guess < number)
{
Console.WriteLine("Too low");
}
else
{
Console.WriteLine("Too high");
}
}
This loop will run forever until the user answers the right question.
the break; statement is used to stop the execution of a loop and completely ignores what comes next, we did break;, so it will just completely disregard the else if and the else and not try to evaluate it, because break; tells the language we're done with this loop, close it.
there's also continue; which acts like break but instead of closing the entire loop, it just closes the current session of the loop, say it's our first loop, we do a continue, we still have some code below, it completely ignores it and starts over.
int x = 0;
while (x < 10)
{
if (x == 5)
{
Console.WriteLine("Continuing.");
continue;
}
Console.WriteLine(x);
x++;
}
see how after the console writing 4, there's Continuing. Instead of 5? Because we check if there's 5 and if so skip over this current loop and go to the next.
For loops.
for loops are similar to while loops but they're specifically used to track a variable, and change it every time the loop is run.
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
Console.WriteLine("Continuing.");
continue; // continue and break also works in for loops.
}
Console.WriteLine(i);
}
- the first part is creating the variable that the for loop will use, int i = 0;
- The second is the condition we use, in this case, the condition is i should be less than 10.
- The last one is the step change, what should happen when every loop finishs, in this case we're doing i++,which increments i by 1.
next, let's explore classes.