top of page

Lesson 4 : Loops And Conditionals

Control the flow of your code by using looping and conditional logic.

Lesson Summary:

Conditional Statements

Sometimes you want to specify whether one thing happens or whether a different thing happens instead. You can use conditionals for this. A conditional statement can be defined by specifying an "if" condition and zero or more alternative conditions (using "else" or "else if"). The following will output "Hello" if the user inputs exactly the text "Flavio" and will say "Goodbye" in every other situation:

   string myInput = Console.In.ReadLine();

   if (myInput == "Flavio")

   {

     Console.Out.WriteLine("Hello");

   }

   else

   {

     Console.Out.WriteLine("Goodbye");

   }

Note the use of "==" instead of "=". The single equal sign is used to assign values. Double equal signs is used to check for two things being equal. Also note that you don't need to use semicolons after the if or else statements; semis are not typically used when following a statement with an opening brace, "{". Also note that string comparisons are case sensitive. That is, if I type "flavio" instead of "Flavio", it will say "Goodbye" instead of "Hello".

Also note that, while this example only has one line of code inside each of the if and else, you can write as much code in there as you want.

You can use else if to make chains of conditions. This will say "Hello to you too" if the input is exactly "Ravioli", and otherwise behave as the previous example:

   string myInput = Console.In.ReadLine();

   if (myInput == "Flavio")

   {

     Console.Out.WriteLine("Hello");

   }

   else if (myInput == "Ravioli")

   {

     Console.Out.WriteLine("Hello to you too");

   }

   else

   {

     Console.Out.WriteLine("Goodbye");

   }

Loops

A loop is a way of repeating a block of code multiple times. You use conditional statements as described above to determine whether a loop will run one more time or whether it will stop. There are multiple types of loops, each serving their own purpose.

while loops

A while loop is a loop which runs a piece of code as long as a condition is met. For example:

   int num = 0;

   while (num < 10)

   {

       num++;

   }

The num++ statement above will keep happening as long as num has a value less than 10, incrementing the value of num on each iteration of the loop. When num finally reaches the value 10, the loop will stop and the program will continue on the code following the right brace, }.

A check is made for the condition (num < 10 in the example above) at two points:

  1) When the while loop is first reached, to determine whether or not to go inside the while loop (this is pretty much exactly like an "if" condition

  2) At the end of each iteration of the while loop, when the } is reached, to check whether to run the loop again. If the condition is met (ie if num is still less than 10 in the above example) then we will go back to the opening brace of the loop, {, and continue from there again, until the while condition is no longer met.

do/while loops

A do/while loop is exactly like a while loop but with one exception: the condition for the loop is only checked at the end of each loop iteration, such that you always enter the loop at least once. Going by the definition of while loops above, it's the same but we exclude check number 1 described there (we don't do a conditional check when the loop is first reached). A do/while loop is defined below:

   int num = 0;

   do

   {

       num++;

   } while (num < 10);

Note the semicolon after the while here. Also note that this result will be the same as for the while loop. A do/while loop is used when it's expected that the while condition might not be met the moment we first get to the loop, but we want to run the loop at least once. This loop is less common than the others, in my personal experience.

for loops

The for loop is generally used when we want to run some code for a specific number of times. For example, when we want to iterate through a list, do something X times, etc. In most cases, all loops can be used interchangeably, but some are more or less convenient for the specific scenario. In contrast with for loops, while loops are typically to keep doing something until some arbitrary condition happens, whereas for loops tend to have an expected end in the horizon.

The most common way of setting up a for loop is for iteration over some provided number. For this relatively common setup, we use a counter and specify 3 things:

   1) What value the counter starts at (for example, 0)

   2) What value the counter should have to keep looping (that is, when to stop)

   3) What to do with the counter after each loop (for example, increment by one)

Here is an example of a for loop configured to loop 10 times, outputting "Hello World" to the console each time. Note that we use the variable i as our counter; we initialize it at (int i = 0), increment by one after each iteration (i++) and continue looping as long as i is less than 10 (i < 10):

   for (int i = 0; i < 10; i++)

   {

      Console.Out.WriteLine("Hello World");

   }

This is the common setup for the for loop, but basically a for loop is just an extension of a while loop, with 3 components separated by semicolons: the middle component is the while loop's condition, the leftmost component is a thing that happens when you first enter the loop, and the rightmost component is something that happens at the end of each iteration.

break

The keyword "break" is helpful when used with loops. It basically breaks out of the current loop you are in, basically teleporting to the line right after the end of the loop's closing brace, }. It works with any loop. For example:

    while (stuff)

    {

        // Do stuff

        break;

        // Everything down here will be skipped

    }

    // After break, you will end up right here.

Note that in the case of nested loops, you will just break out of the inner-most loop

    while (stuff)

    {

        while (moreStuff)

        {

          // Do stuff

          break;

          // Everything down here will be skipped

        }

        // After break, you will end up right here.

   } // The break used here will not break out of this outer loop

while (true)

In the video I have an example that uses "while(true)". This is basically a loop that continues forever unless you do something like "return" (see lesson 5 on functions) or break. There are mixed opinions out there as to whether or not these loops should be totally avoided. I used an example in the video in order to ensure you recognize this when you see it, because these happen to be used with some frequency in code out there. The typical use for while(true) is as follows (in pseudocode):

  while(true)

  {

     // do stuff, compute whether or not "shouldStopLoop" is true

     if (shouldStopLoop)

     {

        break; // This exits the while(true) loop

     }

   }

Additional Notes and Tips:

The variable "bool"

Just like you can store a string like "Hello" into a string variable and a number like 5 into an int variable, you can store a conditional expression into a variable of type bool. For example:

   bool isTrue = true;

   bool isFalse = false;

   bool isGreaterThan5 = myNum > 5;

   bool isEqualToFlavio = myInput == "Flavio";

Note the use of = to assign values and == to test for equality, as before.

These bools can be used for conditionals such as if and else if statements, as well as while, for and do/while loops. For example:

   bool isGreaterThan5 = myNum > 5;

   if (isGreaterThan5)

   {

   }

   while (isGreaterThan5)

   {

   }

   do

   {

   }while (isGreaterThan5);

Note that the following are equivalent:

  if (isGreaterThan5)

  {

  }

  if (isGreaterThan5 == true)

  {

  }

   

Boolean operators

There are many operators that can be used to do conditional stuff. We learned about == and > but there are many others. Here is a short (but not exhaustive) list:

== : is equal to

> : is greater than

< : is less than

>= : is greater than or equal to

<= : is less than or equal to

!= : is not equal to

Also, the operator ! can be used to flip the value of a boolean. For example:

   bool isNotGreaterThan5 = !isGreaterThan5;

Note that the following are equivalent, for a boolean variable isGreaterThan5:

  if (!isGreaterThan5)

  {

  }

  if (isGreaterThan5 != true)

  {

  }

  if (isGreaterThan5 == false)

  {

  }

There are also other operators such as the following, some of which will be covered in more depth in the Addendum, Boolean Logic:

|| : or

&& : and 

Boolean operations and types

We've seen that some operators, such as +, act differently based on the variable's type. It's important to realize that the boolean operators in the previous section also behave differently depending on the variable type. For example, see the following:

  int num1 = 11;

  int num2 = 5;

  if (num1 > num2)

  {

  }

In this example, we will enter the if statement. However, note this example:

  string num1 = "11";

  string num2 = "5";

  if (num1 > num2)

  {

  }

In this example, we will NOT enter the if statement. The reason is that the operator > behaves differently for different types such as int and string. For ints, it will compare the actual value of the number (11 is greater than 5 in value). For strings, however, it does something different: it compares the alphabetical order of the strings. Alphabetically, 1 comes before 5 much like a comes before b. In alphabetical terms, "11" will come before "5" much like "aa" will come before "b".

Be careful with this!

The keyword "continue"

The keyword continue is very similar to break, but instead of breaking out of the loop right away, it immediately moves on the the next iteration of that loop, ignoring whatever follows the continue within the current iteration.

   for(int i = 0; i < 10; i++)

   {

      // Do stuff

      if (something)

      {

        continue;

      }

     // If you hit the continue, everything down here is skipped and it goes to the next iteration

   }

For example, if i is 5 and you hit the continue, it will skip everything after that and go back to the top, setting i to 6.

This is used less commonly than break, but it can be useful if there is some condition that causes you to want to keep iterating. The above is basically the same as this:

   for(int i = 0; i < 10; i++)

   {

      // Do stuff

      if (!something)

      {  

        // This is akin to the second comment in the prior example

      }

   }

Addendum : Boolean Logic

Addendum

Learn about expressing statements as true or false in a variety of different ways.

Practice: Improved Calculator

Practice

Our first "calculator" was crummy. Let's make a better one that actually gives some options.

bottom of page