C# Tutorial Part 5.2 – Complicated If Statements

Welcome to the third part of the fifth part of my C# tutorial. Last time I listed all the logical and relational operators and gave you plenty of time to practise using them. I expect you mostly understand them now, but there were a few loose ends left to tie up:

This was how I said logical operators were used

if((Time = “Evening”)&(PersonName = “Bob”)) //If the time is the evening and the name is Bob
{
   Console.WriteLine(“Good evening, Bob!”); //Print: Good evening, Bob!
}

Alternatively, | (or) could have been used.

But what is the difference between && and &, and || and | ?
Notice they are both used to join two separate logical checks into one condition to test for your if statement. The double signs do this more efficiently – using either of the ‘and’ operators means the if statement’s code will only be run if both checks are true. Putting ‘&’ would check both conditions, then run the code if they were both correct. However, putting ‘&&’ would check the first condition, and if it is false, skip the if statement’s code, because even if the second condition was true, the code still wouldn’t be run because the first was false.
Doing this saves time. It wouldn’t save very much, of course, but if you had an ‘and’ check being run repeatedly over and over again, the saved time might accumulate to something.
The same thing happens with the ‘or’ operators. Putting ‘|’ between two checks would check both and if either was true, run the code. However, putting ‘||’ would skip the second check if the first check was true, and run the if statement’s code, because only one is required to be true for the code to be run.

What is ^ (XOR)?
The XOR (‘exclusive or’) operator is similar to or, but will only run the if statement’s code if only one of the conditions is correct. (It could be either). Or will run if A or B or both is correct, whereas XOR will not run if they are both correct.

What does ! (not) do?
The ! (not) operator simply flips the value of a check. Put it in front of the check you want to flip (with the check in brackets). We have already looked at this with boolean variables.

if (!(Mood == Happy)) //Code block only runs if mood is not equal to happy

if((Time == Morning) && (!(Price >= 10))) //If the time is morning and price is not greater than or equal to 10

Nested If Statements

Last lesson I demonstrated how a nested if statement could be used instead of the & operator:

if(PersonName == “Bob”)
{
   if(Time == “Evening”)
   {
      Console.WriteLine(“Good evening, Bob!”);
   }
}

This is in no way better than using & or &&, but it shows that it is possible to have if statements within if statements, if you ever need to use it.

If Else

Suppose you wanted to print the price of a fast food meal in a console application: It’s quite straightforward – you wouldn’t even need an if statement. What if there was a £1.00 discount for people 40 years old or over? You would need to ask the customer their age and change the price based on that. Let’s say the non-discounted price is £5.00 and we have a variable for the age of the customer called CustomerAge, which has already been given a value. You would have to write something like this

if(CustomerAge >= 40)
{
   Console.WriteLine(“You get the discounted price of £4.00”);
}
   if(CustomerAge < 40)
{
   Console.WriteLine(“Meals cost £5.00”);
}

That’s two if statements in a row which works reasonably well in this instance. However it would not be very good for toggling something; look at this:

if(MusicVolume == 100)
{
   MusicVolume = 0;
}
if(MusicVolume == 0)
{
   MusicVolume = 100;
}

This is supposed to be the simple code that runs when a mute button is pressed: If the music is 100% volume it is changed to 0%, and if it is 0%, it is changed to 100%.

Unfortunately there is a big flaw – can you identify it? If you haven’t already, try running through the code with an original volume of 100: You want to end up with a volume of 0… but instead it just changes back to 100. I discovered this problem as a bug in one of my Scratch games, but after figuring out what the problem was, immediately sorted it out with an if/else statement:

if(MusicVolume == 100)
{
   MusicVolume = 0;
}
else
{
   MusicVolume = 100;
}

Note: This button only works if the only possible values of the volume variable are 0 and 100. You could just have a boolean variable called SoundMute which would make it a lot easier.

As you can see, the else goes after the if statement and uses its condition – if the condition is false the else’s code block runs, then the program continues to run whatever is after the if/else statement.

In the next installment of the tutorial I will look at another form of selection: Switch statements.

I apologise for the lack of indentation in the bits of code in this instalment of the tutorial – I’m writing it on a mac at school. (I’ve finished my Media Studies work. I thought I’d do something productive – flash games bore me a bit anyway.) The mac may have corrected some words according to the american spelling system, but I guess that’s ok. I suppose I have some viewers in the US.

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