In this section, I will review with you the basics of branching. It is a fundamental part of any programming language. It is similar to the basic martial arts in Kung-fu.
What is a branching structure? Attack or defend, attack, wait, no no… defend. The boxer is wondering whether to attack or defend in this case. Don't worry, the branching structure will help the boxer decide which option. I've rambled on about fighting again. But hopefully easy to understand branching structure. The branching structure helps to make a decision, no matter what the situation, fighting or coding. I will go deeper into the field of coding. J)
In C# we have branching structures: If, If-else,
switch.
1. If, If - else
Form: If(Boolean expression)
{
//Code
}
Code is executed only when the Boolean expression is true.
For example
Here is the result:
If the statement flow chart
Here, the resulting output to the screen will be executed, when the condition i < j is true.
Try to guess the result of the following code:
Let see the if-else construct. The if-else construct will allow the program to execute a piece of code when the Boolean expression is false.
For instance:
In this case, it is easy to see that i is not greater than j. So the code in the else part will be executed and output to the output screen:
2. Switch
It allows multiple branches like if-else, in which there must be one or more cases and a default case is required.
Form:
Switch(expression)
Case1: Code block 1
Case2: Code block 2
…
Default:
Let see the below example
Result is:
The above constructs all help the program to make a decision about which code to execute. The question is when to use which structure? This requires each coder to practice a lot, and accumulate more experience for themselves. Personally, when deciding to branch based on a constant value, I would use a switch, it makes the code easy to read, and easy to debug.



0 nhận xét:
Đăng nhận xét