Loops

So far, we’ve talked about if() statements and if/else statements to handle the flow of code execution in our programs. These tools are handy, but they’re not enough to handle the sorts of sophisticated logic that most programs require.

Consider the following situations:

  1. A game that needs to run continously until the player exits.
  2. A program that needs to print the grades for all of the students in a class.
  3. A login prompt for a website accepts user login info and keeps printing error messages until they enter their credentials properly.
  4. A function that prints the sum of the first n numbers, where n is a parameter that’s passed in.

What do all of these situations have in common? They will all require code that is run repeatedly many times.

This is where loops come in. In C#, they come in two basic forms: while loops, and for loops:

while loops

Let’s jump right in with a simple example of a ‘while’ loop.

This loop will print numbers to the console from 1 to 100:

int number = 1;

while(number <= 100)
{
	Console.WriteLine(number);
	number = number + 1;
}

This is called a “while” loop, and if you think its structure is similar to an if() statement, you’re right! A while loop consist of:

  1. the word ‘while’, followed by parenthesis with a boolean expression inside.
  2. Curly braces that tell the program which code to run repeatedly while the condition is true. The program will check the conditions between the parenthesis, and as long as they remain true, it will run the loop again.

In this example, the number gets incremented by one each loop = so once it reaches 101, then the loop condition is no longer true.

Crucially - there needs to be code inside the function that will allow the loop to eventually exit - otherwise you’ll be stuck in an infinite loop!

Here’s another example of a while loop to handle a simple password entry:

bool enteredCorrectPassword=false;
string password = "1234";
while(!enteredCorrectPassword)
{
	Console.WriteLine("Please enter the secret password: ");
	string enteredPassword = Console.ReadLine();
	if(enteredPassword == password)
	{
		Console.WriteLine("Correct!");
		enteredCorrectPassword = true;
	}
	else
	{
		Console.WriteLine("WRONG!");
	}
}

There are a couple things to notice here:
First - we are using the “!” symbol in our while() loop, which means “NOT”. In other words, the expression:

!enteredCorrectPassword

is true, if enteredCorrectPassword is false, and false if the variable is true.

Second - We have an if() statement inside our while() loop. You can ‘nest’ if statements inside loops, loops inside if() statements, and even put multiple “nested” if statements inside each other!

Practice Time!

  1. Write your own while() loop that will add up the first 100 integers, and then print the total value at the end.
  2. Write a version of the password-checking loop, except it should allow for two possible secret passwords.