For this lesson, I want to cover int and double, talk about arithmetic and comparison operators, and introduce if statements. There’s some skipping around on skill levels here so make sure to spend some time with each concept. It might seem boring writing simple addition programs, but it really is important to understand those little tasks you’ll repeat time and time again in more complicated programs.
Previous lessons here:
- Lesson 1: Hello World! Programming with C++ for Beginners
- Lesson 1.5: Continuing with Hello World! Programming with C++ for Beginners
- Snap! (BYOB): Lesson 4: Building a Number Comparison Block Using a Reporter and How It Translates to C++
A type is simply the word that precedes our variables. You’re telling the compiler the type of information held in the variable. Is it a whole number? Is it a decimal? Is it a letter?
The values of variables are stored somewhere in an unspecified location in the computer memory as zeros and ones. Our program does not need to know the exact location where a variable is stored; it can simply refer to it by its name. What the program needs to be aware of is the kind of data stored in the variable. It’s not the same to store a simple integer as it is to store a letter or a large floating-point number; even though they are all represented using zeros and ones, they are not interpreted in the same way, and in many cases, they don’t occupy the same amount of memory.
You can read more about variables and types on cplusplus.com
When you’re starting in programming, you won’t need most types. For whole values, int usually works; for decimal values, double usually works. You don’t need the others unless you’re working with very large values. After getting familiar with those two, I recommend understanding char, bool, void, and null pointer. Although, null pointer is way down the road. For this lesson, we only need int and double.
In practice, that looks like this:
Notice what happens if I switch the types:
We get an error warning:
This warning won’t stop the program from building. It simply states that by naming the decimal value an int, we are changing its value. Watch what happens when we run the program:
For the most part, you want to avoid doing this. However, it’s a nice trick to know and could come in handy when writing programs. Also note that naming the whole number a double didn’t cause an error or change its value — it’s just unnecessary.
Operations of addition, subtraction, multiplication and division correspond literally to their respective mathematical operators. The last one, modulo operator, represented by a percentage sign (%), gives the remainder of a division of two values.
You can read more about arithmetic operators on cplusplus.com
Addition, subtraction, multiplication, and division work as usual. There is one thing I want to point out here. Remember if you’re working with decimal values, you want a double, not an int. Look at the screenshot below and spot the error:
The mistake seems obvious when isolated, but it’s easy to make within a larger program. When this code is run, we get the following answer:
Again, the decimal value is dropped which gives us an incorrect answer.
One more thing of note is the modulo operator. If you’re interested in Computer Science, or just want to program, you should get familiar with modulus math. You won’t use it everyday, but it will absolutely come up. Luckily, it’s simple to understand..
First, I want to demonstrate the difference between the division and modulus symbols. Those are the two signs you’re likeliest to mix up.
And we get…
The division problem gives back expected results. However, the modulus math gives back 0. The modulo operator simply divides the number until there’s a remainder and gives back that remainder. You’ll likely see these problems in reference to the 12-hour clock. This is sometimes referred to as “clock math.”
An example is 14 mod 12
The answer is 2. You can look at it as the 14 “wrapping around” the clock, then starting over once it hits 12, or 14 divided by 12 and giving back the remainder. You don’t need the specific formulas for programming, just an understanding of the answer you’re getting back.
To learn more:
Also, don’t forget your order of operations! PEMDAS* applies.
*For now, avoid testing exponents. Writing 2^2 is not how we use exponents in C++ programming. To read about the power function, click here. You must include the cmath library when using the power function.
Relational and Comparison Operators
Two expressions can be compared using relational and equality operators. For example, to know if two values are equal or if one is greater than the other.
The result of such an operation is either true or false (i.e., a Boolean value).
I’ll show examples with these operators in the next section, but there’s something I want to mention beforehand.
Look at the first operator, equal to, represented by two equals signs. It is very similar to the assignment operator, a single equals sign. Remember the assignment operator is when we write something like int number = 5 (e.g. when we assign a value to a variable). Confusing the two is probably one of the most common mistakes for beginning programmers. Even if you know the difference, even if you’re careful — trust me, you’ll make that silly mistake. Always check your operators if something isn’t working right.
Let’s use what we’ve covered so far in the introduction to if statements below…
Putting it All Together: The if Statement
The if keyword is used to execute a statement or block, if, and only if, a condition is fulfilled. Its syntax is:
if (condition) statement
Here, condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is not executed (it is simply ignored), and the program continues right after the entire selection statement.
Learn more about the if statement on cplusplus.com
There are several conditionals in C++. For now, I’ll introduce the if statement and dive into the rest in the next lesson.
Using the equal to operator:
The variable named number is assigned value 5. The if statement has a condition saying that if the variable number is equal to 5, then print the string to the console. The condition is met so we get the following:
The following condition is not met:
So the statement after the if statement is simply ignored and the program ends.
Notice what happens if we forget the extra equals sign:
We get a warning but it’s vague:
The program runs but nothing was really compared so we get an incorrect result:
Using the not equal operator:
The other operators work exactly the same way. Simply plug in the condition you want to meet, then tell the compiler what it should do next. Don’t forget proper parenthesis (around the condition) and brackets (around the thing that should happen).
You can use additional if statements separately to produce different outcomes. In other words, your program can say, “Hey if this condition is met then do the thing.” That condition is checked, if met, it does the thing. If not met, the next if is checked, “Hey if this condition is checked then do the thing.” And so on. Here’s an example:
Run the code:
You can also do nested ifs. This means putting an if statement inside an if statement and executing something if all conditions are met:
Nested ifs don’t have a limit. You can put if inside an if inside an if and so on. But that does get rather messy looking after awhile. Later on, you’ll learn different conditionals that would better suit that situation. There’s nothing wrong with a few if statements, but anything more than a handful would benefit from something cleaner. But it works nonetheless so play around with it. Learn where the brackets should go as you nest deeper and deeper — bracket placement is very important in programming.
This is all must-know information for beginners.
- You don’t need to memorize every type, but make sure you know the ones to use often (int and double). At least familiarize yourself with the rest so you know what’s available.
- Know the arithmetic operators by heart. Get familiar with mod math if you’re not already.
- Look over the comparison table. Understand the order of symbols. Lesser or equal to is represented by the lesser symbol < and equals symbol =. If you reverse them, your code is wrong. Know the difference between the assignment operator and equal to operator (one sign versus two, completely different meanings).
- Practice the if statement. Build a simple program then add to it. Get creative and bring in as much variety as you can while keeping things in working order.
- This is also a good time to practice writing clean code. As you start writing longer programs, make sure things look nice! Look for proper indentation, spaces to avoid clutter, brackets on their own lines, well-named variables, comments that describe what’s going on.