One reason computer programs are interesting is that they can appear to change behavior. The key to this flexibility is the condition structure. Before I launch into a definition of the condition structure, take a look at the Hi Bill game.
To illustrate the point of conditions–and their cousin, the if statement–I wrote a program that checks whether the user is Bill Gates. (I’m sure that Bill is hanging out at the bookstore as I write this, eagerly waiting to buy this book.) Just in case, I’ll be ready. Here’s the source code for the Hi Bill program:
using System; namespace AreYouBill { /// <summary> /// Demonstrates the If Statement /// </summary> class AreYouBill { static void Main(string[] args) { string fullName; Console.Write("Please enter your full name: "); fullName = Console.ReadLine(); //basic if statement if (fullName == "Bill Gates") { Console.WriteLine("Nice job on C#, Bill."); } // end if //if - else - statement if (fullName == "Bill Gates") { Console.WriteLine("C# is pretty cool"); } else { Console.WriteLine("Sorry, I was looking for Bill"); } // end if //if - else if structure if (fullName == "Bill Gates") { Console.WriteLine("C# is pretty cool"); } else if (fullName == "James Gosling"){ Console.WriteLine("Java is pretty cool"); } else { Console.WriteLine("Nice to see you, {0}!", fullName); } // end if //hold for user response Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Please press enter key to continue"); Console.ReadLine(); } // end main } // end class } // end namespace
The program does exactly what you expect: It asks the user for a name and responds appropriately, as you can see in Figures 2.6, 2.7, and 2.8.
The key to a computer’s decision-making capability is the condition. A condition is an expression that can be evaluated as true or false. In C#, conditions are always surrounded by parentheses, and they usually compare a value to a variable. In the Hi Bill program, the first condition looks like this:
(fullName =="Bill Gates")
The term fullName is the name of a variable. The two equal signs (==) check for equality. This condition checks whether the variable fullName is equal to the value "Bill Gates". Table 2.2 illustrates the various kinds of operators that can be used inside conditional statements.
Operator | Meaning | Sample Condition |
---|---|---|
< | Is less than | (x < 5) |
> | Is greater than | (x > 5) |
== | Is equal to | (x == 5) |
<= | Is less than or equal to | (x <= 5) |
>= | Is greater than or equal to | (x >= 5) |
!= | Is not equal to | (x != 5) |
Please notice that the equality operator is two quote signs, not one. All the comparison operators can be used with any numeric or string values. If you use greater than or less than operators on string values, the computer compares the values in alphabetical order. In other words, ("Apple" < "Zebra") evaluates to true because Apple falls earlier than Zebra in alphabetical order. In essence, Apple is less than Zebra.
When assigning a value to a variable, use one equal sign (=). When comparing a variable to another variable or a value, use two equal signs (==). Many programmers forget this and use a single equal sign when they should use two. C# does not compile but often gives you a strange error, such as "cannot implicitly convert type 'string' to 'bool'.” (Other languages, such as C, do compile and subsequently cause problems with the program that are hard to track down.) If your program is not working, make sure that you are using the comparison operator (==) inside your conditions.
The most common place to use a conditional structure is inside an if statement. The if statement is basic. Here’s the simplest if statement in the Hi Bill program:
//basic if statement if (fullName == "Bill Gates") { Console.WriteLine("Nice job on C#, Bill."); } // end if
The code starts with the keyword if, followed by a condition. In this case, the condition checks whether the fullName variable (entered by the user) is equal to the value "Bill Gates". After the condition, you see a line of code (that writes out a message, in this case) between a pair of braces({}). If the condition is true, all the statements inside the braces are executed. If the condition is false, the computer skips all the instructions inside the braces and move on to the next instruction after the right brace (}). You can have as many lines of code as you like between the braces.
Sometimes you want the computer to do one thing if the condition is true and something else if the condition is false. For example, in the Hi Bill program, you want the computer to say one thing if Bill Gates is the user but something else if the user is not Bill.
In these circumstances, you can use a special addition to the if statement: the else clause. Take a look at the following segment of the Hi Bill program to see how the else clause works:
//if - else - statement if (fullName == "Bill Gates") { Console.WriteLine("C# is pretty cool"); } else { Console.WriteLine("Sorry, I was looking for Bill"); } // end if
You can see that the code starts out the same way as the simple if statement, but after the first right brace (}), I added the else clause and another left brace ({). All the code between the condition and the else statement will be executed if the condition is evaluated to true. The code between else and the last right brace will execute if the condition is false.
If you are making a more complex comparison, you can also check for multiple conditions. The following code fragment checks for Bill Gates or James Gosling (the author of the Java programming language):
//if - else if structure if (fullName == "Bill Gates") { Console.WriteLine("C# is pretty cool"); } else if (fullName == "James Gosling"){ Console.WriteLine("Java is pretty cool"); } else { Console.WriteLine("Nice to see you, {0}!", fullName); } // end if
After the keyword else, you can place another if statement to check for another condition. In this type of structure, the program checks the first condition. If it’s true, the program executes the code after that condition and proceeds to the next line after the end of the entire if structure. If the initial condition is false, the program checks each succeeding condition. If none of the other conditions are true, the program executes the code following the else clause. You can use as many else if structures as you like, as long as you are careful to end each one with a right brace.
Putting in a plain old else clause (without a condition) is a good idea even if you don’t think you will need it. The else clause is a great place to trap any unforeseen situations and respond to them.
3.145.179.59