Conditional Logic is all about the IF word. In fact, it's practically impossible
to programme effectively without using IF. You can write simple programmes
like our calculator. But for anything more complicated, you need to get the
hang of Conditional Logic.
As an example, take the calculator programme you have just written. It only has a Plus button. We'll be adding another button soon, a Subtract button. Now, you can't say beforehand which of the two buttons your users will click. Do they want to add, or subtract? You need to be able to write code that does the following:
The next few lines are our IF Statement:
In between the curly brackets of the IF statement, we have a simple MessageBox line. But this line will only get executed IF buttonClicked has a value of true.
Let's try it out. Start a new project for this (File > New Project). Add a button to your new form, and set the Text property to "IF Statement". Double click the button, and add the code from above. So your coding window will look like this:
Run your programme and click the button. You should see the message box.
Now halt the programme and change this line:
The reason that nothing happens is that our IF Statement is checking for a value of true:
The whole point of using IF ..Else Statements, though, is to execute one piece of code instead of some other piece of code.
But else if is just the same as if, but with the word else at the start.
In fact, we can now add a minus button to our calculator. We'll use else if.
So open up your calculator project again. To do this, click the link on the Start Page Tab in Visual C#. If you can't see your Start Page tab, click its icon at the top of the C# software:
(In version 2012, click View > Start Page from the menu at the top.)
You should then see a section headed Recent Projects:
Look for your calculator project here. You can also click File > Recent
Projects from the menu bar at the top.
If both of those fail, click File > Open Project. Navigate to where you saved your project. Open up the file that ends in .sln.
With your calculator project open, add a new button. Set the following properties for it in the Properties Window:
Now add the following code inside of the Minus button:
All we've done here is to set up two Boolean variables. We've set them both
to false outside of the code. (They have been set up outside of the code because
other buttons need to be able to use them; they have been set to false because
no button has been clicked yet.) When the Minus button is clicked, we'll set
the Boolean variable minusButtonClicked to true and the plusButtonClicked
to false.
But the first two lines are exactly the same as for the Plus button:
Now access the code for your Plus button. Add two lines of code to the end:
So the only thing you are adding is this:
The reason we're resetting these Booleans variables is because we can use them in an if else statement. We can add up if the plusButtonClicked variable is true, and subtract if minusButtonClicked is true.
We'll still do the calculating in the Equals button. So change your equals button to this:
We're using Conditional Logic to decide which of the two buttons was clicked.
The first IF statement checks if the plusButtonClicked variable
is true. If it is, then the addition gets done (this is exactly the same
as before). If the first IF Statement is false, then C# moves down to the else
if statement. If minusButtonClicked is true, then the subtraction
gets done instead. The only difference between the addition and subtraction
lines is the Operator symbols: a plus (+) instead of a minus (-).
The final two lines of code are the same as before - convert the number to text and display it in the text box, and then reset the total1 variable to zero.
Run your calculator and try it out. You should be able to add and subtract!
Exercise D
Finish your calculator by adding Divide and Multiply buttons to your form. Write the code to make your calculator Divide and Multiply.
For this exercise, you're just adding two more Boolean variables to your code. You can then add more else if statements below the ones you already have. You'll also need to add two more lines to the code for your four Operator buttons. These two lines need to reset the Boolean variables to either true or false. For example, here's the code for the Minus button to get your started:
So we now have four Boolean variables outside the button code, one for the
plus button, one for minus button, one for divide button, and one for the multiply
button. When you click a button, its Boolean variable gets set to true.
Do the same for the other three buttons. Then write your else if statements. This is quite a tricky exercise, though. Probably your hardest so far!
After the word switch, you type a pair of round brackets. In between
the round brackets, you type what you want to check for. You are usually testing
what is inside of a variable. Then type a pair of curly brackets. In between
the curly brackets, you have one case for each possible thing that your
variable can contain. You then type the code that you want to execute, if that
particular case is true. After your code, type the word break. This enables
C# to break out of the Switch Statement altogether.
We'll use our calculator as a coding example.
Our four buttons set a Boolean variable to either true or false. Instead of doing this, we could have the buttons put a symbol into a string variable. Like this:
In between the round brackets after the word switch, we've typed the
name of our variable (theOperator). We want to check what is inside of
this variable. It will be one of four options: +, -, *, /. So after the first
case, we type a plus symbol. It's in between double quotes because it's
text. You end a case line with a colon:
Because you need to learn these Operators, let's get some practice with them.
Start a new project. Add two text boxes and a button to your form. Resize the text boxes and type 8 as the Text property for the first text box, and 7 as the Text property for the second text box. Set the Text property for the button to the word "Compare". Your form will then look like this:
Double click the button to get at the coding window. What we'll do is to get
the numbers from the text boxes and test and compare them. So the first thing
to do is to set up some variables:
So in between the round brackets after if, we have our two variables.
We're then comparing the two and checking to see if one is Greater Than
( > ) the other. If firstNumber is Greater Than secondNumber
then the message box will display.
Run your programme and click your button. You should see the message box display. Type a 6 in the first text box, and click the button again. The message box won't display. It won't display because 6 is not greater than 7. The message box code is inside of the curly brackets of the IF Statement. And the IF Statement only gets executed if firstNumber is Greater Than secondNumber. If it's not, C# will just move on to the next line. You haven't got any more lines, so C# is finished.
Stop your programme and go back to your code. Add a new if statement below your first one:
Run your programme, and type a 6 in the first text box. You should see your new message box display. Now type an 8 in the first text box, and click your button. The first message box will display. Can you see why? If your programme doesn't work at all, make sure it is like ours in the image below:
With your programme still running, type a 7 in the first box. You will then
have a 7 in both text boxes. Before you click your button, can you guess what
will happen?
The reason that nothing happens at all is because you haven't written any code to say what should happen if both numbers are equal. For that, try these new symbols:
Another Conditional Operator to try is Not Equal To ( != ). This is an exclamation mark followed by an equals sign. It is used like this:
You can even use the exclamation mark by itself. You do this when you want to test for a false value between the round brackets after if. It's mostly used with Boolean values. Here's an example:
Try not to worry if you don't have a thorough grasp of all the Conditional Operators yet - you'll get the hang of them as you go along. But try the next exercise.
Exercise F
Write a small programme with a text box and a button. Add a label to ask people to enter their age. Use Conditional Logic to test how old they are. Display the following messages, depending on how old they are:
Because you need to learn these Operators, let's get some practice with them.
Start a new project. Add two text boxes and a button to your form. Resize the text boxes and type 8 as the Text property for the first text box, and 7 as the Text property for the second text box. Set the Text property for the button to the word "Compare". Your form will then look like this:
Double click the button to get at the coding window. What we'll do is to get
the numbers from the text boxes and test and compare them. So the first thing
to do is to set up some variables:
So in between the round brackets after if, we have our two variables.
We're then comparing the two and checking to see if one is Greater Than
( > ) the other. If firstNumber is Greater Than secondNumber
then the message box will display.
Run your programme and click your button. You should see the message box display. Type a 6 in the first text box, and click the button again. The message box won't display. It won't display because 6 is not greater than 7. The message box code is inside of the curly brackets of the IF Statement. And the IF Statement only gets executed if firstNumber is Greater Than secondNumber. If it's not, C# will just move on to the next line. You haven't got any more lines, so C# is finished.
Stop your programme and go back to your code. Add a new if statement below your first one:
Run your programme, and type a 6 in the first text box. You should see your new message box display. Now type an 8 in the first text box, and click your button. The first message box will display. Can you see why? If your programme doesn't work at all, make sure it is like ours in the image below:
With your programme still running, type a 7 in the first box. You will then
have a 7 in both text boxes. Before you click your button, can you guess what
will happen?
The reason that nothing happens at all is because you haven't written any code to say what should happen if both numbers are equal. For that, try these new symbols:
Another Conditional Operator to try is Not Equal To ( != ). This is an exclamation mark followed by an equals sign. It is used like this:
You can even use the exclamation mark by itself. You do this when you want to test for a false value between the round brackets after if. It's mostly used with Boolean values. Here's an example:
Try not to worry if you don't have a thorough grasp of all the Conditional Operators yet - you'll get the hang of them as you go along. But try the next exercise.
Exercise F
Write a small programme with a text box and a button. Add a label to ask people to enter their age. Use Conditional Logic to test how old they are. Display the following messages, depending on how old they are:
The two ampersand together (&&) mean AND. You use them like this:
You can test for only one condition of two being met. In which, use the OR ( | | ) operator. The OR operators is two straight lines. These can be found above the back slash character on a British keyboard, which is just to the left of the letter "Z". (The | character is known as the pipe character.) You use them like this:
If all that sounds a bit complicated, don't worry about it - you'll get more practice as we go along
In the next section, we'll have a look at loops, which are another crucial hurdle to overcome in programming. By the end of the section, you'll have written your own times table programme.
Loops are an important part of any programming language, and C# is no different. A loop is a way to execute a piece of code repeatedly. The idea is that you go round and round until an end condition is met. Only then is the loop broken. As an example, suppose you want to add up the numbers one to ten. You could do it like this:
Start a new project by clicking File > New Project from the menu bars at the top of Visual Studio. Now add a button to the new form. Double click the button to get at the code. To quickly add a code stub for a loop, right click anywhere between the curly brackets of the button code. From the menu that appears, click on Insert Snippet:
When you click on Insert Snippet, you'll see a list of items:
Scroll down and double click on for. Some code is added for you:
It all looks a bit complicated, so we'll go through it. Here's the for loop
without anything between the round brackets:
The default round-bracket code that C# inserts for you is this:
And here's the second part:
And here's the third part:
Number 1 on the list above (Which number do you want to start at?) is this:
Number 2 on the list above (How many times do you want to go round and round?) was this:
But you don't need to call the variable length. It's just a variable name, so you can come up with your own. For example:
Number 3 on the list above (How do you want to update each time round the loop? ) was this:
So to recap, you need a start value for the loop, how many times you want to go round and round, and how to get from one number to the other.
So your three parts are these:
The actual code for the loop, the code that goes inside of the curly brackets,
is this:
The second time round the loop, the figures are these:
The third time round the loop:
And the fourth:
Notice how the value of i increases by one each time round the loop.
If you first do the addition after the equals sign, the above will make more
sense! (As an exercise, what is the value of answer the fifth time round the
loop?)
Run your programme, and click the button. The message box should display an answer of 5050
What we'll do is to get the start value and end value from the text boxes.
We'll then use these in our for loop.
So double click your button to get at the code (or press F7 on your keyboard). Set up two variables to hold the numbers from the text boxes:
For the second part, we've changed this:
Run your programme and type 1 in the first text box and 10 in the second text box. Click your button. You should find that the message box displays an answer of 45.
Can you see a problem here? If you wanted to add up the numbers from 1 to 10, then the answer is wrong! It should be 55, and not 45. Can you see why 45 is displayed in the message box, and not 55? If you can't, stop a moment and try to figure it out.
(There is, of course, another problem. If you don't type anything at all in the text boxes, your programme will crash! It does this because C# can't convert the number from the text box and store it in the variable. After all, you can't expect it to convert something that's not there! You'll see how to solve this at the end of the chapter.)
As an example, take the calculator programme you have just written. It only has a Plus button. We'll be adding another button soon, a Subtract button. Now, you can't say beforehand which of the two buttons your users will click. Do they want to add, or subtract? You need to be able to write code that does the following:
IF the Plus button was clicked, add up
IF the Minus button was clicked, subtract
You can rearrange the two statements above. IF the Minus button was clicked, subtract
Was the Plus button clicked? Yes, or No?
Was the Minus button clicked? Yes, or No?
So the answer for each is either going to be Yes, or No - the button is either
clicked, or not clicked.Was the Minus button clicked? Yes, or No?
IF Statements
To test for YES or NO values, you can use an IF statement. You set them up like this:
if ( )
{
{
}
So you start with the word if (in lowercase), and type a pair of round
brackets. In between the round brackets, your type what you want to check
for (Was the button clicked?). After the round brackets, it's convenient (but
not strictly necessary) to add a pair of curly brackets. In between your curly
brackets, you type your code. Your code is what you want to happen IF the
answer to your question was YES, or IF the answer was NO. Here's a coding
example:
bool buttonClicked = true;
if (buttonClicked = = true)
{
{
MessageBox.Show(“The button was clicked”);
}
Notice the first line of code:
bool buttonClicked = true;
This is a variable type you haven't met before - bool. The bool is short
for Boolean. You use a Boolean variable type when you want to check
for true or false values (YES, or NO, if you prefer). This type of variable
can only ever be true or false. The name of the bool variable above is buttonClicked.
We've set the value to true.The next few lines are our IF Statement:
if (buttonClicked == true)
{
{
MessageBox.Show(“The button was clicked”);
}
The double equals sign ( ==) is something else you need to get used to when
using IF Statements. It means "Has a value of". The double equals
sign is known as a Conditional Operator. (There are a few others that
you'll meet shortly.) But the whole of the line reads:
"IF buttonClicked has a value of true"
If you miss out one of the equals signs, you'd have this:
if (buttonClicked = true)
What you're doing here is assigning a value of true to the variable buttonClicked.
It's not checking if buttonClicked "Has a value of" true. The difference
is important, and will cause you lots of problems if you get it wrong! In between the curly brackets of the IF statement, we have a simple MessageBox line. But this line will only get executed IF buttonClicked has a value of true.
Let's try it out. Start a new project for this (File > New Project). Add a button to your new form, and set the Text property to "IF Statement". Double click the button, and add the code from above. So your coding window will look like this:
bool buttonClicked = true;
to this
bool buttonClicked = false;
So the only change is from true to false. Run your programme again, and click
the button. What happens? Nothing!The reason that nothing happens is that our IF Statement is checking for a value of true:
if (buttonClicked == true)
C# will only execute the code between the curly brackets IF, and only IF,
buttonClicked has a value of true. Since you changed the value to false, it
doesn't bother with the MessageBox in between the curly brackets, but moves
on instead.Else
You can also say what should happen if the answer was false. All you need to do is make use of the else word. You do it like this:
if (buttonClicked = = true)
{
{
}
else
{
else
{
}
So you just type the word else after the curly brackets of the IF
Statement. And then add another pair of curly brackets. You then write your
code for what should happen if the IF Statement was false. Change your code
to this:
if (buttonClicked = = true)
{
{
MessageBox.Show("buttonClicked has a value of true");
}
else
{
else
{
MessageBox.Show("buttonClicked has a value of false");
}
So the whole thing reads:
"IF it's true that buttonClicked has a value of
true, do one thing. If it's not true, do another thing."
Run your programme, and click the button. You should see the second MessageBox
display. Halt the programme and change the first line back to true.
So this:
bool buttonClicked = true;
instead of this:
bool buttonClicked = false;
Run the programme again, and click the button. This time, the first message
box will display.The whole point of using IF ..Else Statements, though, is to execute one piece of code instead of some other piece of code.
Else ... If statements in C# .NET
nstead of using just the else word, you can use else if, instead. If we use our calculator as an example, we'd want to do this:
bool plusButtonClicked = true;
bool minusButtonClicked = false;
bool minusButtonClicked = false;
if (plusButtonClicked = = true)
{
{
//WRITE CODE TO ADD UP HERE
}
else if (minusButtonClicked = = true)
{
else if (minusButtonClicked = = true)
{
//WRITE CODE TO SUBTRACT HERE
}
So the code checks to see which button was clicked. If it's the Plus Button,
then the first IF Statement gets executed. If it's the Minus Button, then the
second IF Statement gets executed. But else if is just the same as if, but with the word else at the start.
In fact, we can now add a minus button to our calculator. We'll use else if.
So open up your calculator project again. To do this, click the link on the Start Page Tab in Visual C#. If you can't see your Start Page tab, click its icon at the top of the C# software:
You should then see a section headed Recent Projects:
If both of those fail, click File > Open Project. Navigate to where you saved your project. Open up the file that ends in .sln.
With your calculator project open, add a new button. Set the following properties for it in the Properties Window:
Name: btnMinus
Font: Microsoft Sans Serif, 16, Bold
Location: Move it to the right of your Plus button
Size: 49, 40
Text: -
Now double click your Minus button to get at its code. Add the following two
Boolean variables outside of the Minus button code, just above it:Font: Microsoft Sans Serif, 16, Bold
Location: Move it to the right of your Plus button
Size: 49, 40
Text: -
bool plusButtonClicked = false;
bool minusButtonClicked = false;
You coding window will then look like this:bool minusButtonClicked = false;
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear( );
txtDisplay.Clear( );
plusButtonClicked = false;
minusButtonClicked = true;
Your coding window will then look like the one below:minusButtonClicked = true;
But the first two lines are exactly the same as for the Plus button:
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear( );
The first line just moves the numbers from the text box into the total1 variable.
The second line clears the text box.txtDisplay.Clear( );
Now access the code for your Plus button. Add two lines of code to the end:
plusButtonClicked = true;
minusButtonClicked = false;
The Plus button resets the Boolean variables. This time, plusButtonClicked
gets set to true, and minusButtonClicked gets set to false. It was the
other way round for the Minus button.minusButtonClicked = false;
The reason we're resetting these Booleans variables is because we can use them in an if else statement. We can add up if the plusButtonClicked variable is true, and subtract if minusButtonClicked is true.
We'll still do the calculating in the Equals button. So change your equals button to this:
The final two lines of code are the same as before - convert the number to text and display it in the text box, and then reset the total1 variable to zero.
Run your calculator and try it out. You should be able to add and subtract!
Exercise D
Finish your calculator by adding Divide and Multiply buttons to your form. Write the code to make your calculator Divide and Multiply.
For this exercise, you're just adding two more Boolean variables to your code. You can then add more else if statements below the ones you already have. You'll also need to add two more lines to the code for your four Operator buttons. These two lines need to reset the Boolean variables to either true or false. For example, here's the code for the Minus button to get your started:
Do the same for the other three buttons. Then write your else if statements. This is quite a tricky exercise, though. Probably your hardest so far!
Switch Statements in C# .NET
An easier way to code the calculator is by using a switch
statement instead of an else if statement. A switch statement allows
you to check which of more than one option is true. It's like a list of if statements.
The structure of a switch statement looks like this:
We'll use our calculator as a coding example.
Our four buttons set a Boolean variable to either true or false. Instead of doing this, we could have the buttons put a symbol into a string variable. Like this:
string theOperator;
private void btnPlus_Click(object sender, EventArgs e)
{
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
txtDisplay.Clear();
theOperator = "+";
}
So the last line of code puts the + symbol into a string variable we've
called theOperator. It will only do this if the button is clicked. The
other buttons can do the same. We can then use a switch statement in our Equals
button to check what is in the variable we've called theOperator. This
will tell us which button was clicked. Here's the code that would go in the
Equals button.
case "+" :
The code to add up goes on a new line. After the code, the break word is used.
So what you're saying is:
"If it's the case that theOperator holds a + symbol,
then execute some code"
We have three more case parts to the switch statement, one for each of the
math symbols. Notice the addition of this, though:
default :
//DEFAULT CODE HERE
break;
You use default instead case just "in case" none of
the options you've thought of are what is inside of your variable. You do this
so that your programme won't crash!break;
C# Operators
You've already met one Conditional Operator, the double equals
sign ( == ). You use this in IF Statement when you want to check if a variable
"has a value of" something:
if ( myVariable == 10)
{
{
//EXECUTE SOME CODE HERE
}
So the above line reads, "IF whatever is inside of myVariable
has a value of 10, execute some code."
Other Conditional Operators you'll use when you're coding are these:Start a new project. Add two text boxes and a button to your form. Resize the text boxes and type 8 as the Text property for the first text box, and 7 as the Text property for the second text box. Set the Text property for the button to the word "Compare". Your form will then look like this:
int firstNumber;
int secondNumber;
Then get the text from the text boxes and store them in the variables (after
converting them to integers first.)int secondNumber;
firstNumber = int.Parse(textBox1.Text);
secondNumber = int.Parse(textBox2.Text);
What we want to do now is to compare the two numbers. Is the first number bigger
than the second number? To answer this, we can use an IF Statement, along with
one of our new Conditional Operators. So add this to your code:secondNumber = int.Parse(textBox2.Text);
if (firstNumber > secondNumber)
{
{
MessageBox.Show("The first number was greater than
the second number");
}
Your coding window will then look like this (our message box above is only
on two lines because it can't all fit on this page):Run your programme and click your button. You should see the message box display. Type a 6 in the first text box, and click the button again. The message box won't display. It won't display because 6 is not greater than 7. The message box code is inside of the curly brackets of the IF Statement. And the IF Statement only gets executed if firstNumber is Greater Than secondNumber. If it's not, C# will just move on to the next line. You haven't got any more lines, so C# is finished.
Stop your programme and go back to your code. Add a new if statement below your first one:
if (firstNumber < secondNumber)
{
{
MessageBox.Show("The first number was less than the
second number");
}
Again, our message box above is spread over two lines because there's not enough
room for it on this page. Your message box should go on one line. But the code
is just about the same! The thing we've changed is to use the Less Than
symbol ( < ) instead of the Greater Than symbol ( > ). We've also
changed the text that the message box displays.Run your programme, and type a 6 in the first text box. You should see your new message box display. Now type an 8 in the first text box, and click your button. The first message box will display. Can you see why? If your programme doesn't work at all, make sure it is like ours in the image below:
The reason that nothing happens at all is because you haven't written any code to say what should happen if both numbers are equal. For that, try these new symbols:
>= (Greater Than
or Equal to)
And these ones
<= (Less Than or Equal to)
Try these new Conditional Operators in place of the ones you already have.
Change the text for your message boxes to suit. Run your code again. When you
click the button, both message boxes will display, one after the other. Can
you see why this happens?Another Conditional Operator to try is Not Equal To ( != ). This is an exclamation mark followed by an equals sign. It is used like this:
if (firstNumber != secondNumber )
{
{
//SOME CODE HERE
}
So, "IF firstNumber is not equal to secondNumber execute some code."You can even use the exclamation mark by itself. You do this when you want to test for a false value between the round brackets after if. It's mostly used with Boolean values. Here's an example:
bool testValue = false;
if (!testValue)
{
{
MessageBox.Show("Value was false");
}
So the exclamation mark goes before the Boolean value you want to test. It
is a shorthand way of saying "If the Boolean value is false". You
can write the line like this instead:
if (testValue == false)
But experienced programmers just use the exclamation mark instead. It's called
the NOT Operator. Or the "IF NOT true" Operator.Try not to worry if you don't have a thorough grasp of all the Conditional Operators yet - you'll get the hang of them as you go along. But try the next exercise.
Exercise F
Write a small programme with a text box and a button. Add a label to ask people to enter their age. Use Conditional Logic to test how old they are. Display the following messages, depending on how old they are:
Less than 16: "You're still a youngster."
Over 16 but under 25: "Fame beckons!"
Over 25 but under 40: "There's still time."
Over 40: "Oh dear, you've probably missed it!"
Only one message box should display, when you click the button. Here's some
code to get you started:Over 16 but under 25: "Fame beckons!"
Over 25 but under 40: "There's still time."
Over 40: "Oh dear, you've probably missed it!"
int age;
age = int.Parse(textBox1.Text);
if (age < 17)
{
{
MessageBox.Show("Still a youngster.");
}
For the others, just add more IF Statements, and more Condition Operators.
You've already met one Conditional Operator, the double equals
sign ( == ). You use this in IF Statement when you want to check if a variable
"has a value of" something:
if ( myVariable == 10)
{
{
//EXECUTE SOME CODE HERE
}
So the above line reads, "IF whatever is inside of myVariable
has a value of 10, execute some code."
Other Conditional Operators you'll use when you're coding are these:Start a new project. Add two text boxes and a button to your form. Resize the text boxes and type 8 as the Text property for the first text box, and 7 as the Text property for the second text box. Set the Text property for the button to the word "Compare". Your form will then look like this:
int firstNumber;
int secondNumber;
Then get the text from the text boxes and store them in the variables (after
converting them to integers first.)int secondNumber;
firstNumber = int.Parse(textBox1.Text);
secondNumber = int.Parse(textBox2.Text);
What we want to do now is to compare the two numbers. Is the first number bigger
than the second number? To answer this, we can use an IF Statement, along with
one of our new Conditional Operators. So add this to your code:secondNumber = int.Parse(textBox2.Text);
if (firstNumber > secondNumber)
{
{
MessageBox.Show("The first number was greater than
the second number");
}
Your coding window will then look like this (our message box above is only
on two lines because it can't all fit on this page):Run your programme and click your button. You should see the message box display. Type a 6 in the first text box, and click the button again. The message box won't display. It won't display because 6 is not greater than 7. The message box code is inside of the curly brackets of the IF Statement. And the IF Statement only gets executed if firstNumber is Greater Than secondNumber. If it's not, C# will just move on to the next line. You haven't got any more lines, so C# is finished.
Stop your programme and go back to your code. Add a new if statement below your first one:
if (firstNumber < secondNumber)
{
{
MessageBox.Show("The first number was less than the
second number");
}
Again, our message box above is spread over two lines because there's not enough
room for it on this page. Your message box should go on one line. But the code
is just about the same! The thing we've changed is to use the Less Than
symbol ( < ) instead of the Greater Than symbol ( > ). We've also
changed the text that the message box displays.Run your programme, and type a 6 in the first text box. You should see your new message box display. Now type an 8 in the first text box, and click your button. The first message box will display. Can you see why? If your programme doesn't work at all, make sure it is like ours in the image below:
The reason that nothing happens at all is because you haven't written any code to say what should happen if both numbers are equal. For that, try these new symbols:
>= (Greater Than
or Equal to)
And these ones
<= (Less Than or Equal to)
Try these new Conditional Operators in place of the ones you already have.
Change the text for your message boxes to suit. Run your code again. When you
click the button, both message boxes will display, one after the other. Can
you see why this happens?Another Conditional Operator to try is Not Equal To ( != ). This is an exclamation mark followed by an equals sign. It is used like this:
if (firstNumber != secondNumber )
{
{
//SOME CODE HERE
}
So, "IF firstNumber is not equal to secondNumber execute some code."You can even use the exclamation mark by itself. You do this when you want to test for a false value between the round brackets after if. It's mostly used with Boolean values. Here's an example:
bool testValue = false;
if (!testValue)
{
{
MessageBox.Show("Value was false");
}
So the exclamation mark goes before the Boolean value you want to test. It
is a shorthand way of saying "If the Boolean value is false". You
can write the line like this instead:
if (testValue == false)
But experienced programmers just use the exclamation mark instead. It's called
the NOT Operator. Or the "IF NOT true" Operator.Try not to worry if you don't have a thorough grasp of all the Conditional Operators yet - you'll get the hang of them as you go along. But try the next exercise.
Exercise F
Write a small programme with a text box and a button. Add a label to ask people to enter their age. Use Conditional Logic to test how old they are. Display the following messages, depending on how old they are:
Less than 16: "You're still a youngster."
Over 16 but under 25: "Fame beckons!"
Over 25 but under 40: "There's still time."
Over 40: "Oh dear, you've probably missed it!"
Only one message box should display, when you click the button. Here's some
code to get you started:Over 16 but under 25: "Fame beckons!"
Over 25 but under 40: "There's still time."
Over 40: "Oh dear, you've probably missed it!"
int age;
age = int.Parse(textBox1.Text);
if (age < 17)
{
{
MessageBox.Show("Still a youngster.");
}
For the others, just add more IF Statements, and more Condition Operators.AND and OR
The final two Operators we'll have a look at are these:
&& (And)
|| (Or)
These two are known as Logical Operators, rather than Conditional Operators
(so is the NOT operator). || (Or)
The two ampersand together (&&) mean AND. You use them like this:
bool isTrue = false;
bool isFalse = false;
bool isFalse = false;
if ( isTrue == false && isFalse == false )
{
{
}
You use the AND operator when you want to check more than one value at once.
So in the line above, you're checking if both values are false. If and ONLY
if both of your conditions are met will the code between curly brackets get
executed. In the code above, we're saying this:
"If isTrue has a value of false AND if isFalse
has a value of false then and only then executed the code between curly brackets."
If isTrue is indeed true, for example, then any code between curly brackets
won't get executed - they both have to be false, in our code.You can test for only one condition of two being met. In which, use the OR ( | | ) operator. The OR operators is two straight lines. These can be found above the back slash character on a British keyboard, which is just to the left of the letter "Z". (The | character is known as the pipe character.) You use them like this:
bool isTrue = false;
bool isFalse = false;
bool isFalse = false;
if ( isTrue == false || isFalse == false )
{
{
}
We're now saying this:
"If isTrue has a value of false OR if isFalse
has a value of false then and only then executed the code between curly brackets."
If just one of our variables is false, then the code in between curly brackets
will get executed.If all that sounds a bit complicated, don't worry about it - you'll get more practice as we go along
In the next section, we'll have a look at loops, which are another crucial hurdle to overcome in programming. By the end of the section, you'll have written your own times table programme.
C# and Loops
We've produced a video to go with this lesson. It's recommended that you read the text below as well, though. The video is here:
Loops are an important part of any programming language, and C# is no different. A loop is a way to execute a piece of code repeatedly. The idea is that you go round and round until an end condition is met. Only then is the loop broken. As an example, suppose you want to add up the numbers one to ten. You could do it like this:
int answer;
answer = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
And this would be OK if you only had 10 numbers. But suppose you had a thousand
numbers, or ten thousand? You're certainly not going to want to type them all
out! Instead, you use a loop to repeatedly add the numbers. answer = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
For Loops in C#
The first type of loop we'll explore is called a for loop. Other types are do loops and while loops, which you'll meet shortly. But the for loop is the most common type of loop you'll need. Let's use one to add up the numbers 1 to 100.Start a new project by clicking File > New Project from the menu bars at the top of Visual Studio. Now add a button to the new form. Double click the button to get at the code. To quickly add a code stub for a loop, right click anywhere between the curly brackets of the button code. From the menu that appears, click on Insert Snippet:
for ( )
{
{
}
So you start with the word for, followed by a pair of round brackets. What
you are doing between the round brackets is telling C# how many times you want
to go round the loop. After the round brackets, you type a pair of curly brackets.
The code that you want to execute repeatedly goes between the curly brackets.
The default round-bracket code that C# inserts for you is this:
int i = 0; i < length; i++
There's three parts to the round-bracket code:- Which number do you want to start at?
- How many times do you want to go round and round?
- How do you want to update each time round the loop?
int i = 0;
What the default code is doing is setting up an integer variable called i (a
popular name for loop variables.) It is then assigning a value of 0 to the i
variable. It will use the value in i as the starting value of the loop. You
can set up your starting variable outside the code, if you prefer. Like this:
int i
for (i = 0; i < length; i++)
{
{
}
So the variable called i is now set up outside the loop. We then just
need to assign a value to the variable for the first part of the loop.Number 2 on the list above (How many times do you want to go round and round?) was this:
i < length;
This, if you remember your Conditional Logic from the previous section, says
"i is less than length". But length is not a keyword. So you need
to either set up a variable called length, or replace the word length with a
number. So either this:
for (int i = 0; i < 101; i++)
Or this:
int length = 101;
for (int i = 0; i < length; i++)
{
}
In the first example, we've just typed the i < 101. In the second example,
we've set up a variable called length, and stored 101 in it. We're then just
comparing one variable to another, and checking that i is less than length:{
}
i < length;
If i is less than length, then the end condition has NOT been met and C# will
keep looping. In other words, "Keep going round and round while i is less
than length."But you don't need to call the variable length. It's just a variable name, so you can come up with your own. For example:
int endNumber = 101;
for (int i = 0; i < endNumber; i++)
{
{
}
Here, we've called the variable endNumber instead of length. The second part
now says "Keep looping while i is less than endNumber".Number 3 on the list above (How do you want to update each time round the loop? ) was this:
i++
This final part of a for loop is called the Update Expression. For the first
two parts, you set a start value, and an end value for the loop. But C# doesn't
know how to get from one number to the other. You have to tell it how to get
there. By typing i++, you are adding 1 to the value inside of i each time round
the loop. (called incrementing the variable). This:
variable_name++
is a shorthand way of saying this:
variable_name = variable_name + 1
All you are doing is adding 1 to whatever is already inside of the variable
name. Since you're in a loop, C# will keep adding 1 to the value of i each time
round the loop. It only stops adding 1 to i when the end condition has been
reached (i is no longer less than length).So to recap, you need a start value for the loop, how many times you want to go round and round, and how to get from one number to the other.
So your three parts are these:
for (Start_Value; End_Value; Update_Expression)
OK, time to put the theory into practice. Type the following for your button
code:
answer = answer + i;
This is probably the trickiest part of loops - knowing what to put for your
code! Just remember what you're trying to do: force C# to execute a piece of
code a set number of times. We want to add up the numbers 1 to 100, and are
using a variable called answer to store the answer to the addition. Because
the value in i is increasing by one each time round the loop, we can
use this value in the addition. Here are the values the first time round the
loop:Run your programme, and click the button. The message box should display an answer of 5050
Loop Start Values and Loop End Values
dd two text boxes to your form. Add a couple of labels, as well. For the first label, type Loop Start. For the second label, type Loop End. Your form will then look something like this:
So double click your button to get at the code (or press F7 on your keyboard). Set up two variables to hold the numbers from the text boxes:
int loopStart;
int loopEnd;
Now store the numbers from the text boxes into the two new variables:int loopEnd;
loopStart = int.Parse(textBox1.Text);
loopEnd = int.Parse(textBox2.Text);
Now that we have the numbers from the text boxes, we can use them in the for
loop. Change you for loop to this:loopEnd = int.Parse(textBox2.Text);
for (int i = loopStart; i < loopEnd; i++)
{
{
answer = answer + i;
}
The only thing you're changing here is the part between the round brackets.
The first part has now changed from this:
int i = 1
to this:
int i = loopStart
So instead of storing a value of 1 in the variable called i, we've stored
whatever is in the variable called loopStart. Whatever you type in the first
text box is now used as the starting value of the loop.For the second part, we've changed this:
i < 101
to this:
i < loopEnd
We're using the value stored inside of loopEnd. We're telling C# to
keep looping if the value inside of the i variable is less than loopEnd.
(Remember, because our Update Expression is i++, C# will keep adding
1 to the value of i each time round the loop. When i is no longer
less than loopEnd, C# will stop looping.)Run your programme and type 1 in the first text box and 10 in the second text box. Click your button. You should find that the message box displays an answer of 45.
Can you see a problem here? If you wanted to add up the numbers from 1 to 10, then the answer is wrong! It should be 55, and not 45. Can you see why 45 is displayed in the message box, and not 55? If you can't, stop a moment and try to figure it out.
(There is, of course, another problem. If you don't type anything at all in the text boxes, your programme will crash! It does this because C# can't convert the number from the text box and store it in the variable. After all, you can't expect it to convert something that's not there! You'll see how to solve this at the end of the chapter.)
0 comments:
Post a Comment