C# Tutorial Part 5.0 – If Statements

Brackets. Done in Inkscape by Fibonacci, simpl...

Image via Wikipedia

Hello and welcome to C# Part 5.0. The next few installments of this tutorial will cover how selection works in C#. Selection is basically when different lines of code run on different conditions. For instance, you could have a program which only says Good Morning to you if it is the morning.
A simple form of selection is an If Statement, which simply checks a condition, then runs its block of code if it the condition was true.
The syntax for an If Statement is this: (Ignore the < >s – they’re just to avoid confusion)

if(<condition>)
{
   <statements>
}

Code within braces (curly brackets { } ) is called a block of code.
Here is how an if statement would work with the example above:

string TimeOfDay = “Morning”;
//We have a string variable called TimeOfDay. It’s not part of the if statement, I’m just showing you where we got it from
if (TimeOfDay == “Morning”)
{
   Console.WriteLine(“Good Morning!”);
}

The computer checks that the value in the variable TimeOfDay is equal to “Morning”, and since it is, runs the code, printing Good Morning.
If I had initialised TimeOfDay as “Afternoon” or anything other than “Morning”, the line which prints the message would not have been run.

Please note how I put ‘==’ instead of just ‘=’. The equals sign on its own, as you know, is the assignment operator. Two equals signs in a row is  the equals logical operator. There are others, which will be covered later in the tutorial.

There was really no point in that if statement, because TimeOfDay had been given a value which couldn’t have changed. The real use for If Statements is when the user inputs something and you want to run some code if it was correct.
For example, in a password system:

string CorrectPassword = “Password”; //I know its a terrible password to use
string UserInputWord;
UserInputWord = Console.ReadLine(); //Let the user have a try at cracking it
if (UserInputWord == CorrectPassword) //If they get it right… Beware – it’s case-sensitive!
{ //Run the code in the block
   Console.WriteLine(“Well done, how did you guess?”);
   //Then print a message so they know they did!
} //Then end the block of code so the rest of the program doesn’t depend on the statement being correct
Console.ReadLine(); //This will run even if the condition is false.

Here is the process the computer goes through, translated roughly into human thought:

Allocate some memory for a string… Give this area of memory the name ‘CorrectPassword’… Give it the value “Password”… Ignore the comments… Allocate some memory for another string… Give this area of memory the name ‘UserInputWord’… Wait for the user to press enter… Give it the value the user has written… Ooh, and if statement… Is the value stored in the area of memory called ‘UserInputWord’ the same as the value stored in the area of memory called ‘CorrectPassword’?

Now, supposing the user entered the correct password, the computer would go on to ‘think’:

OK the values are the same therefore the condition is true which means I have to run the code in the block belonging to the if statement… Here’s the curly bracket which starts the block… Print the string value “Well done, how did you guess?”… Here’s another curly bracket which means the block is over… Wait for the enter key to be pressed… End program… Job well done

However, if the user did not enter the correct password, the computer would have ‘thought’ this instead:

The values are not equal so the condition is false. I will not run the block belonging to the if statement… Here’s the curly bracket which signifies the start of the block… I will ignore everything until I reach the curly bracket which signifies the end of the block… here it is… now I can run the rest of the statements… Wait for the enter key to be pressed… End program… Job well done

It is not only strings that can be used in if statements – you can compare any sort of values you like:

Console.WriteLine(“What is 5 plus 7?”);
int TriedNumber = Convert.ToInt16(Console.ReadLine());
if (TriedNumber == 5+7)
{
   Console.WriteLine(“Well done!”);
}

The section of code above checks that a value entered by the user is equal to the answer to the calculation 5+7.

Console.WriteLine(“What’s 3 times nine?”);
bool UserCorrect = false;
int EnteredNumber = Convert.ToInt16(Console.ReadLine());
if (3*9 == EnteredNumber)
{
   UserCorrect = true;
}
if (UserCorrect)
{
   Console.WriteLine(“Well done!”);
}

The section of code above demonstrates that a boolean variable can be used as a condition

That’s all for this simple introduction to If statements. The next installment of the tutorial will focus on the logical operators available to enhance your conditions!



I have just checked through this part of the tutorial and found that the last two sections of code produced errors when run in C#. That was my fault for not typing them up correctly, and also the fault of Visual Basic for teaching me some bad practises. Normally I check all the code works before I publish the tutorial, but I had to write this part on a computer which did not have C# installed. I have now fixed the errors. Sorry for any confusion caused – I will try hard to prevent it in future. I am currently working on the next part of the tutorial, which covers Logical Operators and Relational Operators to use in if statements.

Advertisements

About Matt

I like writing, filmmaking, programming and gaming, and prefer creating media to consuming it. On the topic of consumption, I'm also a big fan of eating.
This entry was posted in Programming and tagged , , , , , . Bookmark the permalink.

Enter comment:

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s