- 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.
- 程序員修煉之道:程序設計入門30講
- Mastering phpMyAdmin 3.4 for Effective MySQL Management
- Xamarin.Forms Projects
- Effective Python Penetration Testing
- C程序設計案例教程
- 3D少兒游戲編程(原書第2版)
- HTML5入門經典
- KnockoutJS Starter
- Arduino家居安全系統構建實戰
- WordPress 4.0 Site Blueprints(Second Edition)
- 一本書講透Java線程:原理與實踐
- Access 2010中文版項目教程
- PHP與MySQL權威指南
- Mastering Concurrency Programming with Java 9(Second Edition)
- Data Science Algorithms in a Week