New Digital Era
Back
Back to index...

Control flow statements

In everyday's life we do tasks like cooking or dishwashing that are not trivial. Cooking is not an easy job! For example, to make a recipe you first have to check if you have all the ingredients, then follow the steps one at a time and check that you are doing it right. You are checking for states, in this case, the state of food. Is the steak done? Not yet. Ok, then wait a bit and check again later. The steps of recipes are often also numbered. First we read instruction number 1, then instruction number 2, ... checking until we reach the last instruction.
All these also applies to algorithms in computers. if we want to print the numbers from 1 to 10000, we can't just write 10000 lines of code, each printing the next number. We have to use a loop. We will now see all the control flow statements:

if
statement

This is probably the most important control statement. The if statement checks a condition. Let's see.

int i = int.Parse(Console.ReadLine());

if (i > 5)
{
    Console.WriteLine("i is greater than 5");
}
else
{
    Console.WriteLine("i is less or equal to 5");
}
                
This is quite of new stuff, isn't it? Let's break it down into parts to see in more detail:
int i = int.Parse(Console.ReadLine());
This isn't a control flow statement but I think it's important you learn this early because it will help you to start building programs. Here we are assigning the result of the function
Parse
, contained in the type
int
, which is in turn being called with a parameter that is the result of a call to the function
ReadLine
of the type Console.

Note: a type is any construct that holds data, functions, or both. There are 2 types of types in C#: reference types and value types. We will look into what this means in a later chapter. For now, you just have to know that when I say type or class, these terms are interchangeable and the meaning of the sentence will stay the same, at least until we see other kinds of types.

The function ReadLine reads a line of text form the console. Go ahead and type the code in visual studio and execute it. The console will wait for you to enter some text. The ReadLine function will end when you press enter, then it will return a
string
with the contents of the text you wrote. You can assign it to a variable or pass it directly as a parameter to another function, as we're doing. Watch out!: the
Parse
function expects a string composed of numbers! Letters or other kind of symbols will make it fail and the program will give you an error.
What
int.Parse
does is convert a number given as a string, for example,
"123"
to an
int
,
123
, which you can then assign to a variable of type
int
.
Now we can focus on if statement.
if (i > 5)
We use the if statement to check a condition. Here, we are checking the variable i to see if it is greater than 5. The condition is always enclosed in parenthesis (), don't forget this! Also, check the full list of comparison operators here.
If the result of the statement is true, the first block will execute. We use braces {} to define a block. If i > 5, then
{
    Console.WriteLine("i is greater than 5");
}
will execute. But if i <= (less or equal to) 5,
{
     Console.WriteLine("i is less or equal to 5");
}
will execute. A block can span as many lines as you want. Here it's only 1 line, but can be infinitely large.
The
else
keyword is used to signal that if the condition is false, then we want to execute an alternative block of code. An alternative if branch is always optional, we could have written the following code:
if (i > 5)
{
    Console.WriteLine("i is greater than 5");
}
This will print "i is greater than 5" to console if it's true, or will do nothing if it's false.
Notice that you don't have to write ; after the if condition check. if you write ; it will mean that the if statement ends right there, and that the blocks that follow it are completely independent. That is not what we want.

The condition of the if statement can also be a complex expression like
i > 0 && i < 10
. This is expresion is only evaluated to
true
when i is greater than 0 and i is less than 10. There are two important things here:
-First, note the operator precedence! This expression is correct because the
<
and
>
operators are evaluated before the logical and
&&
. Here is an example of an expression that needs parenthesis to be correct to do what it's meant it to do:
int myVar = 16;
if (myVar + 10 / 2 == 13)
{
    Console.WriteLine("This expression is malformed!");
}

if ((myVar + 10) / 2 == 13)
{
    Console.WriteLine("This expression is correct.");
}
This code will only print the second statement. It's obvious that 16 + 10 is 26, and then 26/2 is 13. But as in a calculator, it will not give your the expected result unless you use parenthesis to override operator precedence. The first expression will evaluate to 16 + 5, which is 21, and 21 is not 13 so it will not execute the body.
In the second if statement, the expression is correctly formed because we are using parenthesis. The operations will evaluate to 13 == 13, which is true, and the body will execute.
You can find more detailed documentation on the operator hierarchy here.
-Second, you can make expressions as complex as you want, but ideally you'd want short expressions rather than long, complicated ones, because the code will be easier to read and mantain. You can always divide a big if statement into nested, smaller statements.

For single-line if statements we can omit the braces and do as follows:

if (i > 5) Console.WriteLine("i is greater than 5");
 
This can sometimes improve the legibility of the code, but also don't abuse it. Also remember that when you don't enclose the branches in braces is only valid to write one line of code for each branch. The following is also valid:
if (i > 5)
    Console.WriteLine("i is greater than 5");
else
    Console.WriteLine("i is less or equal to 5");
See that you can also write the single line of code of each branch on the next line, it doesn't have to be directly after the if condition check. You can also write one branch with the single-line syntax and the other with braces, if you need more than 1 line of code for it:
if (i > 5)
{
    Console.WriteLine("i is greater than 5");
}
else Console.WriteLine("i is less or equal to 5");
                
It's good manners to know which syntax style to use when programing, not just using what you feel like using randomly. I will explain the rules I follow for each situation: You don't have to follow this, it's just my recommendation based on what I like.

for
statement

The for statement is used to loop a defined number of times. Let's see an example:
Console.WriteLine("Numbers from 1 to 10");
for(int i = 1; i <= 10; i++)
{
    Console.WriteLine(i);
}
Let's see what happening here. First of all, we have a new keyword:
for
.
for
has 3 parts, each separated by ';'. The first part is the for initializer. This corresponds to
int i = 1
in the code. This part lets us create a variable that we'll use to iterate. For example, I am creating a variable called
i
that I'll use to count from 1 to 10.
In this part, you can create and initialize a new variable, assign an existing variable, or leave empty and do nothing at all.
In the next part, which corresponds to
i <= 10
in the code, is the condition statement. For will keep looping as long as this condition is true. In this case, the condition is that
i
has to be less or equal to 10. If this condition is true, the body of the loop will execute. If it's false, the
for
will end.
The next part,
i++
, it's the post part. This statement is executed after the body of the for loop has executed. In this case, we increment the value of the variable
i
with the
++
operator, called postfix increment operator, which increases the value of the variable that precedes it by 1. This only works for integer (byte, short, int, long and their unsigned variants) variables. Then the check is done again if it is still true the body will execute again. Here is a list with the flow of this chunk of code, in order.
  1. int i = 1;
  2. i <= 10
    is
    true
  3. Console.WriteLine(i) //i is 1
  4. i++ //i is incremented and is now 2
  5. i <= 10
    is
    true
  6. Console.WriteLine(i) //i is 2
  7. i++ //i is incremented and is now 3
  8. i <= 10
    is
    true
  9. Console.WriteLine(i) //i is 3
  10. i++ //i is incremented and is now 4
  11. ...
  12. i <= 10
    is
    true
  13. Console.WriteLine(i) //i is 10
  14. i++ //i is incremented and is now 11
  15. i <= 10
    is
    false

It's also important to mention the keyword
break
. This keyword, when used inside the body of a loop (not only the
for
loop, but any loop) will terminate the execution of the loop immediately, jumping to the next instruction after the loop. Let's see an example:
for(int x = 0; x < 10; x++)
{
    if (x == 5) break;
    Console.WriteLine(x);
}
Console.Write("Finished");
Try to guess what it will print before executing it.
Here we are interrupting the loop when
x
5, even if the loop iterates from 0 to 9. As a result, it will print the numbers from 0 to 4, and once
x
is 5,
break
will cause the loop to terminate.

You can nest all these statements one inside another to build more complex applications.

Your turn:

Proposed tasks for IF
  1. Ask a number to the user with the console, read it, and print "{the number here} is a positive number" if the number is positive, or "{the number here} is a negative number" if the number is negative, or print "{the number here} is 0" if the number is 0.
  2. Ask a number to the user with the console, read it, and print "Fizz" if the number is divisible by 3. You can use the
    %
    operator (the modulo operator) to computer the remainder of a division. For example, 4 % 2 will give you 0(because 4 is divisible by 2 and so the remainder is 0), but 4 % 7 will give you 4.
  3. Do the same as in the previous task, but print "Buzz" if the number is divisible by 5.
  4. Do the same, but print "FizzBuzz" if the number is both divisible by 3 and 5 at the same time.
  5. Now combine all 3. Ask a number, and print "Fizz" if it is only divisible by 3, "Buzz" if it is only divisible by 5, or "FizzBuzz" if it is divisible by both 3 and 5. If none of these conditions apply, just print the number.
Proposed tasks for FOR
  1. Print all the numbers from 0 to 1000;
  2. Print all the numbers that are divisble by 2 from 0 to 1000;
  3. Print all the numbers form 0 to 1000000 but stop the loop if the iteration number is divisible by 9844;
  4. Print the multiplication table of all the number from 1 to 10. Do it with only 2 for loops.
  5. Ask two numbers, a and b, and print all the numbers in the [a, b] range. If a == b, print "a must be greater than b!" Note: '[' means inclusive and '(' means exclusive.
  6. Do the same, but allow any 2 numbers as long as they are not the same number. If the second number is smaller than the first, you have to iterate backwards.
Next
Back to index...