Previous C++ programming lessons:
For this lesson, I want to wrap-up if statements and introduce logical operators.
if and else
Recall the if statement produces different results depending on the condition that’s met. The following example from Lesson 2 initializes variable age, asks for user input, stores user input into age, then uses the value in age to test conditionals.
There’s an easier way to implement the same logic and that’s with a selection statement.
Selection statements with if can also specify what happens when the condition is not fulfilled, by using the else keyword to introduce an alternative statement. Its syntax is:
if (condition) statement1 else statement2
where statement1 is executed in case condition is true, and in case it is not, statement2 is executed.
Same program using else:
Although both codes work similarly and produce identical results, the second example makes better logical sense. If someone’s age is not equal to or greater than 18, it’s safe to assume their age is under 18. We don’t need to test a second conditional, just let the program know, “Hey, if this condition isn’t met, then it’s definitely this other thing.”
We can also use multiple if else statements. Take a look at the following code and outputs:
That is pretty much all there is to using if else. A few things to remember: Don’t leave dangling ifs or elses and be careful with brace placement. Remember that errors seem obvious when isolated, but they’re easy to make when you’re writing hundreds of lines of code. Take a moment to review the errors below:
First, here’s a simple program that uses if else:
Let’s say I want a program with 4 age groups with different ticket prices:
- ages 5 and under get in free
- ages 6 – 12 pay $5
- ages 13 – 64 pay $10
- ages 65 and older get a senior discount for $7
How would that look with the if (condition) else if (condition) else format? Well the conditional order would have to look like this:
If the user enters 17, the first condition is checked and unsatisfied, the second condition is checked and satisfied, the output is given, other conditions are skipped, and the program ends. This works if and only if the age brackets follow this order. Let’s see what happens if the age brackets are flipped.
I’ll admit this example might not be the greatest argument in favor of logical operators. You might think, what’s the big deal? I’ll just use the first order. That works in this case but there are times when you want to pass several criteria and the order isn’t the only obstacle. Sure, nested ifs can check multiple conditions, but they get messy fast. A good rule of thumb is to remember when things start looking messy in C++, there is probably a neater way to get the job done.
&& Operator (And)
In the next example, I’m keeping the second order of conditions but inserting logical operators to make it work:
Line 14 says, if the age is greater than 5 and less than 13 do the following. Line 16 says, if the age if greater than 12 and less than 65 do the following.
The double ampersand says the thing on the left and the thing on the right must meet the conditions. If either is not met, the overall test failed.
You can use multiple and operators, mix and match logic operators, and test different variables. Valid uses:
- if (number > 10 && number < 100 && number != 50)
- if (number > 30 && name == “Sarah”)
- if ((number < 1000 && word == "pickaxe") || word == "sword")
*Notice the extra parenthesis in the third statement. QtCreator gives a warning if those parenthesis are left out. Adding the parenthesis rids the warning and eliminates any ambiguity. We’re asking to check that the number is less than 1000 and the word is pickaxe. That’s one condition. OR the word can be sword and it doesn’t matter if the left side is true or false. The following section explains the or operator.
|| Operator (Or)
The or operator is similar to the and operator in that it checks both sides. Instead of saying this condition AND this condition need met, it says, this condition OR this condition need met. In other words, only one side can satisfy the conditional and pass the test.
There are pretty cool possibilities with logical operators, especially when you get into functions and arrays. You could build a game with items a character can use in different ways. The pseudocode could look like:
if (item == “bow” || item == “axe” || item == “wand”)
…bounce off to a function that equips item as a weapon
else if (item == “cloak” || item == “shield”)
…bounce off to a function that equips item as protection
ignore the item or assume it’s this other thing
You can read more about logical operators on cplusplus.com
Here’s more on C++ operators and examples on tutorialspoint.com
More on truth tables from Wikipedia.org
- Write a simple program using if and else. Initialize a variable that takes a number. If the number is over 50, print something to the console. Else print something else.
- Write a program using if and else that resembles the movie ticket program in this lesson. Can you make it work with 5 or more categories?
- Write a program that resembles the characters/weapons/armor scenario described in this lesson, ignoring the bouncing off to a function part. Instead, have the output tell the user whether the item is a weapon, armor, or something else.
Writing sample exercises is encouraged, but I’d be lying if I said I wrote every sample exercise in my C++ books. You should at least be able to mentally write the code. If you can’t imagine how an exercise is written, take a crack at it or review the material before moving on.
Next lesson: C++ loops and increment/decrement operators