- 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.
- Spring 5.0 By Example
- Hands-On Machine Learning with scikit:learn and Scientific Python Toolkits
- Three.js開發(fā)指南:基于WebGL和HTML5在網(wǎng)頁上渲染3D圖形和動(dòng)畫(原書第3版)
- 老“碼”識(shí)途
- Mastering Python High Performance
- C程序設(shè)計(jì)案例教程
- 劍指MySQL:架構(gòu)、調(diào)優(yōu)與運(yùn)維
- ANSYS Fluent 二次開發(fā)指南
- 單片機(jī)C語言程序設(shè)計(jì)實(shí)訓(xùn)100例
- 創(chuàng)意UI:Photoshop玩轉(zhuǎn)APP設(shè)計(jì)
- Hadoop大數(shù)據(jù)分析技術(shù)
- Mastering Leap Motion
- Java EE程序設(shè)計(jì)與開發(fā)實(shí)踐教程
- Parallel Programming with Python
- Django 2.0 入門與實(shí)踐