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

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.

主站蜘蛛池模板: 仲巴县| 北京市| 安乡县| 徐水县| 朝阳县| 东丽区| 新丰县| 海兴县| 泸定县| 永新县| 舟曲县| 龙山县| 碌曲县| 江永县| 龙泉市| 惠州市| 恩平市| 库尔勒市| 南康市| 邵阳市| 花垣县| 龙陵县| 金湖县| 合江县| 包头市| 海兴县| 高平市| 东明县| 胶州市| 巨野县| 德格县| 红河县| 嵊泗县| 会东县| 前郭尔| 全南县| 隆安县| 增城市| 天水市| 明溪县| 项城市|