Discussion 10-11

If statements

Today we talked about if statements. If/else statements let us make our program run different code depending on the values of inputs or other variables. For a basic example of the syntax, we wrote absoluteValue.cpp.

We also talked about how to write various conditions in the if statement. For example:


Up to now, if our program asks for input and the user types something that makes no sense, the programs have just failed - either by crashing or by outputting nonsense results. With if statements, we can make the program detect input mistakes and output an appropriate error message. For example, we wrote areaOfRectangle.cpp. Using if statements, we're able to print an error message and exit if the user types letters instead of numbers, or if they type a negative number or 0.

Incidentally, here is a modified version of the area-of-rectangle program that uses the "or" operator || to make the if blocks simpler. Take a look at what I moved around to accomplish this!

Google searches

Here are some Google searches you could try if you're having trouble with today's material. I'm deliberately trying to choose search terms that you could have thought of yourself!