官术网_书友最值得收藏!

The if statement

The if statement is a decision statement that could branch one or more statements to evaluate. This statement consists of a Boolean expression. Let's consider the problem of finding vowels in a book that was discussed on day one. Let's write this using the if statement:

private static void IfStatementExample() 
{ 
WriteLine("if statement example."); 
Write("Enter character:"); 
char inputChar = Convert.ToChar(ReadLine()); 
 
//so many if statement, compiler go through all if statement 
//not recommended way 
if (char.ToLower(inputChar) == 'a') 
WriteLine($"Character {inputChar} is a vowel."); 
if (char.ToLower(inputChar) == 'e') 
WriteLine($"Character {inputChar} is a vowel."); 
if (char.ToLower(inputChar) == 'i') 
WriteLine($"Character {inputChar} is a vowel."); 
if (char.ToLower(inputChar) == 'o') 
WriteLine($"Character {inputChar} is a vowel."); 
if (char.ToLower(inputChar) == 'u') 
WriteLine($"Character {inputChar} is a vowel."); 
} 

In the preceding code, we are using only the if condition. However, the preceding code is not a recommended code, but this is just there to showcase the usage of the if statement. In the preceding code snippet, once the code executes a compiler, it verifies all if statements without caring about the scenario where my first if statement got passed. Say, if you enter a, which is a vowel in this case, the compiler finds the first expression to be true and prints the output (we get our result), then the compiler checks the next if statement, and so on. In this case, the compiler unnecessarily checks the rest of all four statements that should not have happened. There might be a scenario where our code does not fall into any of the if statements in the preceding code; in that case, we would not get the expected result. To overcome such situations, we have the if...else statement, which we are going to discuss in the upcoming section.

主站蜘蛛池模板: 应用必备| 平江县| 固安县| 柘城县| 鹿泉市| 宜兰市| 通许县| 固原市| 莱西市| 邯郸县| 库车县| 石门县| 饶阳县| 平江县| 鄂温| 双桥区| 共和县| 信阳市| 石渠县| 临清市| 正安县| 多伦县| 南乐县| 平顶山市| 六枝特区| 闵行区| 垦利县| 永修县| 来宾市| 玛纳斯县| 张掖市| 嘉禾县| 长兴县| 兴和县| 汶上县| 兰溪市| 霍林郭勒市| 安化县| 襄汾县| 宽城| 工布江达县|