Learn How to Program in Cby
|
Notice that there are different outcomes, whether the condition is met or not. This is the essence of a conditional. Let's try an example of a logical operator in a conditional statement. In this example, we want to test whether the viewer was born between 1980 and 1989, making him/her a "child of the 80s." We put the two conditions (year > 1979 and year < 1990) in the same if statement, like this:
The logical operator "and" && tests whether both conditions are true. If they are, then the viewer is a child of the 80s. If they are not both true, then the viewer was not born in the 80s. Type this source code in your editor and save it as log.c then compile it, link it, and run it. Using two logical operatorsNow let's try one with both a logical "and" && and a logical "or" ||. Let's see whether you were born during Democratic presidential years (in the US) or during Republican presidential years. In the second half of the 20th century, five US presidents were Republican: Eisenhower (1953-1961), Nixon (1969-1974), Ford (1974-1975), Reagan (1980-1988), and Bush (1989-1992). Let's write a conditional that includes all of these Republican years: if(((year > 1952) && (year < 1962)) || ((year > 1968) && (year < 1976)) || ((year > 1979) && (year < 1993))) Here is how we write the program:
We put the logical "or" || between each of the Republican presidential years, to test if the person was born during any of these years. Remember to count your parentheses ( ), because it's easy to forget one. If you get an odd number, then you've missed one. Type this source code in your editor and save it as pres.c then compile it, link it, and run it. Conditional OperatorIf you have to compare two numbers, to determine which is bigger or smaller, use the conditional operator. The conditional operator has three parts:
Put these three parts together and have them equal a variable, like this: This says, "If year1 is less than year2, then the answer is year1. If year1 is NOT less than year2, then the answer is year2. That's how the conditional operator works. Let's try it with a real example. Who is older, your Mother or your Father? Here is a program to find out:
Type this source code in your editor and save it as condop.c then compile it, link it, and run it. If your parents were born during the same year, then this program will default to say that your Father is older. This isn't a good result, so in the next section, we'll learn how to handle multiple conditions. |
||||||||||||
|
Copyright © 2001 Kristin Switala |
|||||||||||||