Saturday, February 26, 2011

If Else Statements

If statements in C# and a lot of other programming languages are used to make choices in your application. Us humans make a lot of choices in life. If you have no ham, then you go to the supermarket to buy ham. You don't want to buy ham if you already have a bunch at home.

Time to show you an example, but first you'll need to create a new console application called "IfStatements".

The following code will be used for the explanation:
//We have a lot of ham, so we don't need more
bool inNeedOfHam = false;

if (inNeedOfHam == true)
Console.Write("Buy ham!");

The variable "inNeedOfHam" will decide if you need ham and for this example you don't need any, so it's set to false.

"(inNeedOfHam == true)" is the condition of the if statement and the signs "==" are the comparison. It will compare the variable "inNeedOfHam" that holds the data false with the data true. False is not equal to true, so the code "Console.Write("Buy ham!");" will not be executed. If you're stubborn, then press F5 on your keyboard (See what I did?). Memorise that "==" will compare data and "=" will assign data.

You will use comparisons for every if statement and "==" is one of many:
== - Exactly equal to
> - Greater than
< - Less than
>= - Greater than or equal to
<= - Less than or equal to
!= - Not equal to
Memorising these will prove useful as almost every application will contain one or more comparisons.

For the next example you will turn your "if statement" into an "if else statement", so it will look like the following:
if (inNeedOfHam == true)
Console.Write("Buy ham!");
Console.Write("I don't need ham");

The else statement will always have the opposite comparison to that of the if statement. In other words: the if statement has the condition "If false is equal to true", so the else statement has the condition "If false is not equal to true". The else statement its condition is true, because false is not equal to true. This means that the code "Console.Write("I don't need ham");" will be executed and "I don't need ham" will be written on your screen. Press F5 on your keyboard to check.

The same can be done for any other data type. An example condition "(5 < 10)" will check if the number 5 is smaller than 10. This condition is true, because 5 is smaller than 10.

Source Code IfStatements Project

>> Arrays And Loops

No comments:

Post a Comment