|
In this tutorial you will experiment with relational operators, Boolean operators, and conditional statements in C, as discussed in Chapter 12. You will be using some example programs in this laboratory. You can use your Web browser to view or download them as you prefer.
Take a look at if-1.c. Try to predict exactly what will be printed out when the program runs. Then compile and run it and see if you were right.
Here is an explanation, keyed to the example numbers from the comments.
Take a look at if-2.c. Try to predict exactly what will be printed out when the program runs. Then compile and run it to see if you were right.
Here is an explanation, keyed to the example numbers from the comments.
hard to understand until you use Emacs to indent it, when the nesting structure should make things clear. Remember: the indenting doesn't mean anything to the C compiler, but it can mean a lot to a human reader.
Take a look at if-3.c. Try to predict exactly what will be printed out when the program runs. Then compile and run it to see if you were right.
The only example that requires an explanation is example 7. It is a common mistake in C to use the assignment operator (=) where the equality operator (==) was intended. Unfortunately, the result is often legal C syntax so the compiler doesn't complain. Even though it is always the case that z == z, the assignment z = z results (in this case) in the else branch being take.
Take a look at if-4.c. Try to predict exactly what will be printed out when the program runs. Then compile and run it to see if you were right.
These examples show how the Boolean operators &&
(and), ||
(or),
and !
(not) can be used to compose more complicated conditions.