THE IF STATEMENT
One of the single most important statements in every programming language is the if statement. Being able to set up conditional blocks of code is a fundamental principal of writing software. In C#, the if statement is very simple to use. If you have already used another programming language, chances are that you can use the if statement of C# straight away. In any case, read on to see how it's used. The if statement needs a boolean result, that is, true or false. In some programming languages, several datatypes can be automatically converted into booleans, but in C#, you have to specifically make the result boolean. For instance, you can't use if(number), but you can compare number to something, to generate a true or false, like we do later on.
In the previous post we looked at variables, so we will expand on one of the examples to see how conditional logic can be used.
We use 2 if statements to check if the entered number is between 0 and 10, and a companion of the if statement: The else keyword. Its meaning should be obvious to anyone speaking English - it simply offers an alternative to the code being executed if the condition of the if statement is not met.
As you may have noticed, we don't use the { and } characters to define the conditional blocks of code. The rule is that if a block only contains a single line of code, the block characters are not required. Now, this seems like a lot of lines to simply check a number, doesn't it? It can be done with fewer lines of code, like this:
We put each condition in a set of parentheses, and then we use the || operator, which simply means "or", to check if the number is either more than 10 OR less than 0. Another operator you will be using a lot is the AND operator, which is written like this: &&. Could we have used the AND operator instead? Of course, we simply turn it around a bit, like this:
This introduces a couple of new operators, the "less than or equal too" and the "bigger than or equal too".
No comments:
Post a Comment