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

  • Learn C# in 7 days
  • Gaurav Aroraa
  • 291字
  • 2021-07-08 09:51:28

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.

主站蜘蛛池模板: 会宁县| 廊坊市| 泸定县| 苗栗县| 长顺县| 聊城市| 南投县| 四川省| 长泰县| 德清县| 泸西县| 施秉县| 盖州市| 保山市| 喀什市| 贵溪市| 翁源县| 巩留县| 汽车| 韶山市| 陇西县| 乌海市| 牡丹江市| 平原县| 临朐县| 綦江县| 江安县| 开阳县| 石阡县| 健康| 墨竹工卡县| 南乐县| 南昌县| 象州县| 大邑县| 广德县| 朝阳市| 丹棱县| 湛江市| 泾源县| 望城县|