It's time to introduce one of the most important aspects of all programming: decision making, when to execute one action or another, and how to execute that action, whether it must be in a loop or a condition will tell us if it should be executed.
Index
1 - Conditional Statements
These are the statements we use when we need to make a decision based on some logic. A way to visualize this: imagine you're driving down a road and there is a fork ahead, taking the fork would be like entering a conditional statement.
1.1 - If-else
The first conditional statement we'll see is the If-Else
statement, which literally means "if-not". Therefore, the conditional statement is tied to a logical operator and is represented as follows:
if (A < B)
{
Console.WriteLine("A es menor que B");
}
else
{
Console.WriteLine("A no es menor que B");
}
If the content inside the if statement is a single line, we don't need to use brackets, but personally, I recommend it because it's easier to read later.
if (A < B)
Console.WriteLine("A es menor que B");
else
Console.WriteLine("A no es menor que B");
Since version 7 of C#, if statements can be written in a single line and are called "one line statements." Be careful when creating them since you can nest as many as you want inside each block, and this can make it hard to follow the logic when reading code. In my work, I've run into cases where you spend more time figuring out what all the nested ifs do than actually fixing the problem itself.
A < B ? Console.WriteLine("A es menor que B") : Console.WriteLine("A no es menor que B");
If you only want to include the option inside the If
because the else will just follow the normal course of execution, you don't need to add the else
.
if (A < B)
{
Console.WriteLine("A es menor que B");
}
1.2 - Switch-case
Many times we find ourselves writing a lot of IF statements one after the other. To solve this, we have the implementation of the switch statement.
A switch statement takes a variable and checks it against each available case. As we see in the example, we write switch(variable)
to analyze the variable. This variable can be of any type, not just a string, it could be a number, a date, etc.
string mes = "enero";
switch (mes)
{
case "enero":
Console.WriteLine("enero tiene 31 dias");
break;
case "febrero":
Console.WriteLine("febrero tiene 28 dias");
break;
default:
Console.WriteLine("mes no encontrado");
break;
}
As we see in the example, we check each case and at the end of each one, we use the break; statement to exit the loop. For this example, we only used two months, so the statement is small, but if we included all months, it would be much larger.
As everyone knows, months (except February) have either 30 or 31 days. The switch statement lets us group cases together to produce the same output for several of them.
string mes = "enero";
switch (mes)
{
case "enero":
case "marzo":
case "mayo":
case "julio":
case "agosto":
case "octubre":
case "diciembre":
Console.WriteLine("enero tiene 31 dias");
break;
case "febrero":
Console.WriteLine("febrero tiene 28 dias");
break;
case "abril":
case "junio":
case "septiembre":
case "noviembre":
Console.WriteLine("febrero tiene 28 dias");
default:
Console.WriteLine("mes no encontrado");
break;
}
With C# 8, its functionality has increased; you can check out more here.
2 - Iterative Statements - Loops
Often when we are programming, we find that we have a list of objects, and for all of them (or most of them, applying conditional statements) we need to calculate some value or display different information to the user. Instead of handling each case one by one, we use loops to iterate over every element in a list.
2.1 - For Loop
The for loop is the most widely used loop and is used to repeat actions a certain number of times.
for (int i = 0; i < 10 ; i++){
Console.WriteLine("Iteración número "+i);
}
When we declare the for loop, we do so with:
- Declaration and initialization of the variable:
int i = 0;
- Logical expression to determine whether to execute:
i < 10;
- Arithmetic increment operator:
i++;
2.2 - While Loop
We evaluate the logical expression inside parentheses and execute the block if it's true. Once finished, we re-evaluate the expression, and if it's still valid, we execute the block again.
int contador = 0;
while(contador < 10){
Console.WriteLine("Iteración número "+i);
contador++;
}
2.3 - Do-while Loop
Similar to the previous one, but in this case, the block is executed at least once and then continues executing as long as the expression remains true.
int contador = 0;
do{
Console.WriteLine("Iteración número "+contador);
contador++;
}while(contador < 10);
Be very careful when creating loops, as it's possible, especially when learning, to create infinite loops. If they happen in your application while developing, you'll get an "out of memory" because the computer runs out of memory and that's it, nothing major.
But if it happens in production, it would cause the application to stop working and it would be a much bigger problem.
Here's one way to create an infinite loop:
int contador = 11;
do{
Console.WriteLine("Iteración número "+contador);
contador++;
}while(contador > 10);
As you can see, the initial value of the contador
variable is greater than 10, so the loop will never stop executing. You'd get the same result if, for example, you didn't include the contador++
statement, since the contador variable would always have the same value.
If there is any problem you can add a comment bellow or contact me in the website's contact form