|
|
|
So far, all of the programs you've written are extremely linear. That is, they always do exactly the same thing. The most interesting variation you can hope for is a program crash when someone enters a bad value! But what if we want our program to react differently under certain situations? What if we want our program to make a decision, based on user input? What "if", indeed. Observe the mighty "if" statement, in all its glory: Console.Write("Enter your age: "); int age = Convert.ToInt32( Console.ReadLine() ); if( age == 16 ) { Console.WriteLine("Hey, that's the age you can get your driver's licence at!"); } The first two lines should be familiar by now... we're asking the user for their age. The next four lines make up our "if" statement. The first line, where the actual "if" occurs, is where we write our logic. Basically, this line says, "if the user's age is precisely 16, then run all the code in between the two { } signs." So if the user enters 16 for their age, they'll get the above message on the screen. In any other case, the code in the "if" statement is simply skipped. Of course, == is not the only comparison we can use. Here's a more complete list: == (equal to) < (less than) > (greater than) != (not equal to) <= (less than or equal to) >= (greater than or equal to) Be careful not to confuse = with ==. Regular old = is used for assigning values, and has virtually nothing to do with "if" statements. == is the one we use to test for equivalence. Also beware of using "==" on such number types as doubles and floats, since it's very rare that a decimal number will exactly equal any particular number you might test for. Regarding the difference between < > and <= >=, just remember that "age < 17" and "age <= 16" are exactly the same test. The first means "any number under 17", and the second means "any number under or including 16", but the resulting logic is exactly the same (they'll both accept any number under 17). All expressions that can be placed in an "if" statement boil down to a Boolean expression... that is, an expression that is either true or false. C# actually provides a datatype to store these results, called "bool". Let's take a look: bool userAgeIs16 = age == 16; if( userAgeIs16 ) { Console.WriteLine("Hey, that's the age you can get your driver's license at!"); } The above code sample does exactly the same thing as the first code sample, except this one stores the "true/false" result in a bool variable, and the drops the result into the "if" statement. I'm mentioning this now, because beginner programmers often get hung up on seeing equations inside "if" statements. They get so used to seeing stuff like "age == 16" in "if" statement expressions, that their eyes bug right out when they see an actual bool variable used, instead. I don't expect (or want) you to start creating Boolean variables all over the place for this specific purpose; I simply want you to keep in mind that all those >/== symbols and numbers you normally put in an "if" statement always boil down to a single Boolean value. Incidentally, you can directly assign true or false to a bool, simply by providing the word true or false as the value (all lowercase, with no quotation marks around it... true and false are special reserved keywords in C#)! What if we wanted our if statement to test multiple things at once? For example, age and IQ? Then, we could do this: Console.Write("Enter your age: "); int age = Convert.ToInt32( Console.ReadLine() ); Console.Write("Enter your iq: "); int iq = Convert.ToInt32( Console.ReadLine() ); if( age >= 16 && iq > 75 ) { Console.WriteLine("You're old enough AND smart enough to drive a car!"); } The &&, which means "AND", allows us to make our "if" statement more specific. Now, you will only get the console message if you enter an age that's greater than or equal to 16, AND you enter an IQ that's greater than 75. If either of those things aren't true, the entire statement is considered false, and the code in the "if" statement will be skipped. The opposite of && is ||, which means "OR". In an OR expression, if any of the statements are true, the entire expression is considered to be true. It reads just like English. If I was to say, "you can buy liquor if you're older than 18, or use fake id", then you would immediately understand that it is possible to buy liquor if you were over 18, OR had fake Id. You don't need to be over 18 AND have fake Id to buy liquor; you only need one of those things... hm, maybe I shouldn't have used an illegal example. Oh, well, I'll bet you understand it now, right? You're also free to "mix and match" all of these operators however you choose. For example, the following expression (although complicated) is perfectly legal: if( (age != 5 && age < 50) || (age > 60 && iq > 90) ) The above expression is true when age is less than 50, but not 5, OR when age is over 60 and iq is greater than 90. It's certainly a mouthful, but it's not too often that you'll see a bigger expression than the one above (evaluated all at once, anyway). In any "mixed" expression like this, && is evaluated before ||. However, you can use brackets to force C# to evaluate the contents of the brackets first. You can also add brackets just to improve readability, as I've done above. Moving right along, it bears mentioning that you can add as many lines of code as you want inside the "if" statement. You can even declare new variables in it... if( age > 15 ) { Console.Write("Now enter your name: "); string name = Console.ReadLine(); Console.WriteLine(name + ", you're old enough to drive!"); } It is very important to note, however, that the variables you declare inside an "if" statement only exist inside that "if" statement. If you try to refer to them outside the "if" statement, your program simply won't work, because those variables don't exist anymore - we say they've gone "out of scope". What if you want to access a variable both inside and after the "if"? Well, then you'd simply declare the variable before the "if", like this... string name = ""; if( age > 15 ) { Console.Write("Now enter your name: "); name = Console.ReadLine(); Console.WriteLine(name + ", you're old enough to drive!"); } Console.WriteLine(name + ", I still know your name!"); ...and there you go. We'll talk more about scope when we get into functions, but for now, just remember: if you want a variable to be accessible for your entire program, don't declare it inside an "if" statement. By the way, if you're only going to include one line in your "if" statement, you don't technically need the { } at all. You can just do this... if( age > 15 ) Console.WriteLine("That works, too!"); Just remember, if you omit the { }, only the first line immediately after the "if" line will be counted as part of the "if". Okay, now let's get a little more sophisticated... if( age > 15 ) { Console.WriteLine("Old enough to drive."); } else { Console.WriteLine("Too young to drive."); } Not only are we telling the program what to do under a certain condition, we're now telling it what to do if that condition isn't met! The optional "else block" in an "if" statement goes right at the end, and works exactly the same way. The main difference is that we don't provide an expression, because "else" works like a "catch all" for any scenario that doesn't match the original test. What if we want several specific scenarios? Well, we can do this: if( age == 16 ) { Console.WriteLine("Just barely old enough to drive."); } else if( age > 15 ) { Console.WriteLine("Old enough to drive."); } else { Console.WriteLine("Too young to drive."); } We can add as many "else if" blocks as we want to an existing "if" statement, to cover additional scenarios. Both the "else if" and "else" blocks are optional in an "if" statement; however, if you have an "else" block, it must be listed last. Additionally, you might be wondering why I bumped the original test, age > 15, down to the "else if". The reason is that, in any if/else if/else structure, C# will only run the first match it encounters. So if age > 15 was listed first, and the user typed in 16 as their age, age > 15 would be the first match the program encountered. It would run the generic "Old enough to drive" logic, and skip over the more specific "Just barely old enough to drive", which is what we actually wanted. Be aware of this when building if statements, and make sure that your first expressions don't "steal" execution from the other expressions. On a lesser note, since an age of 16 is now explicitly covered in the first expression, we could change the second expression to evaluate age > 16 (so that an age of 16 will no longer match it). It won't change how the program works, but if someone's reading the code, they might find it confusing that 16 actually matches two different expressions in the "if" statement. It may not sound like a big deal, but in general terms, a programmer should write their code so that their intent is as obvious as possible (comments can help in this regard). We've covered a lot of ground, but we're just getting started with flow control! The "if" statement is the foundation of programming logic, but there are still many powerful and time-saving mechanisms that you still need to know about. Before we move on, however, consider the following code sample... using System; namespace A_If { class Class1 { [STAThread] static void Main(string[] args) { // Prompt for age Console.Write("Enter your age: "); int age = Convert.ToInt32( Console.ReadLine() ); // Basic if/else if/else if( age == 16 ) { Console.WriteLine("Hey, that's the age you can get your driver's license at!"); } else if( age < 16 ) { Console.WriteLine("You're too young to drive. Sorry!"); } else if( age > 16 && age < 150 ) { Console.WriteLine("You could already have your driver's license by now."); } else { Console.WriteLine("Yeah, right."); } // Single line if statement if( age < 0 ) Console.WriteLine("Hey, wait a second! You can't have a negative age!"); // Boolean variables are what "fuel" if statements bool oldEnough = age >= 18; if( oldEnough ) Console.WriteLine(Environment.NewLine + "You are old enough to vote."); else Console.WriteLine(Environment.NewLine + "You are too young to vote."); // "or" logic Console.Write(Environment.NewLine + "Enter a number divisible by four OR five: "); int num = Convert.ToInt32(Console.ReadLine()); if( (num % 4 == 0) || (num % 5 == 0) ) Console.WriteLine("Correct."); else Console.WriteLine("Incorrect."); // "and" logic Console.Write(Environment.NewLine + "Enter a number divisible by four AND five: "); num = Convert.ToInt32(Console.ReadLine()); if( (num % 4 == 0) && (num % 5 == 0) ) Console.WriteLine("Correct."); else Console.WriteLine("Incorrect."); // Prompt for exit Console.Write(Environment.NewLine + "Program complete! Hit enter to exit..."); Console.ReadLine(); } } } |
|