C++ Lesson 3: Continuing with If Statements and Introducing Logical Operators

Previous C++ programming lessons:

Lesson 1: Hello World! Programming with C++ for Beginners

Lesson 1.5: Continuing with Hello World! Programming with C++ for Beginners

C++ Lesson 2: Data Types, Arithmetic Operators, Comparison Operators, and Introduction to If Statements.

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.

Screenshot (448)
If age is greater than or equal to 18, print this. If age is less than 18, print that.

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:

Screenshot (456).png
It’s okay to omit brackets here

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:

Screenshot (457)
Silly program but sound logic
Screenshot (458)
First condition is satisfied, output Is given, other conditions are skipped, program ends
Screenshot (459)
First condition is not met, the else is checked and satisfied, last condition is skipped, program ends
Screenshot (460)
First two conditions are not met, logically it must be this last thing so we don’t need to check any conditions

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:

Screenshot (461).png
There is an extra if on line 15. Always end with an else.
Screenshot (462).png
There is an if where there should be an else on line 15.
Screenshot (463).png
Braces on lines 12 and 14 break up the if and else. Notice that errors are not always on the line with faulty code. Errors aren’t necessarily broken themselves, instead they break other code.
Screenshot (464).png
Braces on lines 12 and 16 prevent the program from compiling.
Screenshot (465)
This compiles and runs, but the braces are unnecessary. Brace placement is something you should test and get comfortable with. They can make or break an entire program.

Logical Operators

First, here’s a simple program that uses if else:

Screenshot (466)
This works but what if we want more age groups?

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:

Screenshot (469).png
We will see why another order falls apart

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.

Screenshot (472).png
Same information, different order
Screenshot (470).png
This works because it satisfies the first condition
Screenshot (471)
This does not work because ANY age over 5 satisfies the second condition, prints to console, and ends the program. The third and fourth conditions are NEVER used.

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:

Screenshot (474).png
This works

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.

Screenshot (480)
truth table

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.

Screenshot (481)
truth table

In practice: 

Screenshot (479).png
The name entered can be Frodo OR Samwise OR Legolas to pass

Screenshot (475)

Screenshot (476)

Screenshot (477)

Screenshot (478)

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

else

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

Sample Exercises

  • 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

Happy Programming!

Advertisements

Comments

One comment on “C++ Lesson 3: Continuing with If Statements and Introducing Logical Operators”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s