Numbers

An introduction to the different types of numbers in C++, and how we can do basic math operations on them.

Ryan McCombe
Updated

Welcome to our exploration of numeric variables! In this lesson, we explore numeric data types and their operations in C++.

Building on our previous discussion about integers and floating-point numbers, we will expand your understanding of how numbers work in C++ and how you can manipulate them.

As a reminder, here is how we create variables. This is similar to what we saw in the previous chapter, except we're now also showing the creation of a float type. A float is a number with a decimal point:

bool isDead { false };
int Level { 5 };
float Armor { 0.2 };
int LargeNumber { 100000000 };

Basic Arithmetic Operators

We can do all the standard maths operations to our numbers. This includes all the basic operators:

  • + for addition
  • - for subtraction
  • * for multiplication
  • / for division

For example, we can use a mathematical expression when setting the initial value of our variable, or updating it:

// Level is initialized with a value of 5
int Level { 2 + 3 };

// It is then updated with the value of 10
Level = 5 * 2;

Here are some more examples:

// Level is initialized with a value of 5
int Level { 2 + 3 };

Level = 5 + 1; // Level is 6
Level = 5 - 1; // Level is 4
Level = 5 * 2; // Level is 10
Level = 6 / 2; // Level is 3
Level = 1 + 2 + 3; // Level is 6

Order of Operations

The order of operations applies in C++ just as it does in maths. Operations are not always performed left-to-right.

For example, multiplication happens before addition, so our following code will result in Level having a value of 7.

The 2 * 3 part of our expression will happen first, then 1 will be added to that result:

// Level is initialized with a value of 7
int Level { 1 + 2 * 3 };

As with maths, we can introduce brackets - ( and ) - to manipulate the order of operations. Expressions in brackets happen first:

// Level is initialized with a value of 9
int Level { (1 + 2) * 3 };

Variables with Maths

We can use the values contained in other variables within our arithmetic expressions:

int StartingHealth { 500 };
int Lost { 100 };

// This will have a starting value of 400
int RemainingHealth { StartingHealth - Lost };

We can also use the current value of the variable when updating it, using an expression like this:

int Level { 5 };
Level = Level + 1;  // Level is now 6

Test your Knowledge

Math with Variables

After running the following code, what will be the value of Health?

int BaseHealth { 200 };
int HealthBuff { 2 };
int Health { BaseHealth * HealthBuff };

After running the following code, what will be the value of Level?

int Level { 10 };
int Level = Level + 1;

Increment and Decrement Operators

The above example of increasing the value contained in a variable by 1 is so common, that programming languages often offer a quicker way of writing it.

Increasing a value by one is commonly called incrementing, and it has a dedicated operator: ++.

The operator can go before or after the variable. There is a subtle difference, which we'll discuss in a later chapter, but for now we can use them interchangeably:

int Level { 5 };
Level++;  // Level is now 6
++Level;  // Level is now 7

We also have the -- operator for decrementing:

int Level { 5 };
Level--;  // Level is now 4
--Level;  // Level is now 3

Compound Assignment

Additionally, we have further operators to provide a quicker way of updating existing variables using arithmetic. These are referred to as compound assignment operators

For example, += will increase the variable on the operator's left by the value on the right.

int Level { 5 };
Level += 3;  // Level is now 8

We also have the -=, *=, and /= operators to apply subtraction, multiplication, or division in the same manner

int Level {8};
Level -= 3; // Level is now 5
Level *= 3;  // Level is now 15
Level /= 5; // Level is now 3

Level *= Level; // Level is now 9

Test your Knowledge

Shorthand Operators

After running the following code, what will be the value of Level?

int Level { 2 };
Level = Level * Level + 2;
Level -= 2;

Negative Numbers

We have access to negative numbers using the - symbol:

int NegativeValue { -5 };

They behave exactly like they would in maths

int Health { 100 };
int HealthModifier { -10 };

Health += HealthModifier; // Health is now 90

Health *= -1; // Health is now -90

When used like this, - is another example of an operator. It is referred to as the unary minus.

The implication of - being an operator means it doesn't necessarily only appear before numbers - it can be applied more widely.

For example, we can access the negative form of a variable, or another expression, by prefixing it with -:

int Input { 4 };
int Result { -Input }; // Result is -4
Result = -(Input + 2); // Result is -6

Integer Division

What would the result be of dividing 5 by 2?

#include <iostream>
using namespace std;

int main(){
  cout << "5 / 2 = " << 5 / 2;
}

Perhaps surprisingly, C++ says it is 2:

5 / 2 = 2

We may have expected it to be 2.5. However, dividing an integer by an integer always yields an integer.

So why is it not 3? The specification of the built-in int data type is to discard any floating point component - not to round it. So, this leaves us with the integer 2.

This is true whatever we do with the result of the expression. Above, we are logging it out, but we could also be assigning it to a variable, even a floating point variable:

// IntegerLevel is 2
int IntegerLevel { 5/2 };

// FloatingLevel is 2.0
float FloatingLevel { 5/2 };

Even though we're assigning the result of the expression to a floating point variable that could store 2.5, the evaluation of 5/2 happens first.

5/2 resolves to 2, and then we convert 2 to a float, which yields 2.0.

Test your Knowledge

Integer Division

After running the following code, what will be the value of Level?

int Level { 3 / 2 };

After running the following code, what will be the value of Level?

float Level { 1 / 2 };

Floating Point Numbers

In the previous example where we cout the result of our division, we saw that the division of two integers always yields an integer. If either, or both, of the values in the expression were floating point numbers, we would get a floating point output instead.

All of these examples would log out 2.5:

cout << 5.0/2;
cout << 5/2.0;
cout << 5.0/2.0;

This is also true for the other basic maths operations. Combining a float and an integer in the same operation yields a float, regardless of whether the float is on the left or the right side of the operator:

5 + 1.0; // 6.0
5.0 + 1; // 6.0

5 - 1.0; // 4.0
5.0 - 1; // 4.0

5 * 2.0; // 10.0
5.0 * 2; // 10.0

5.0 / 2; // 2.5
5 / 2.0; // 2.5

We can create floating point variables in the way you might expect:

float Health { 2.5 };

A float variable can be initialized with an integer value, which will be converted to its floating-point representation

float Health { 5 }; // Health is 5.0

Like with any other variable, we can initialize it with an expression. For example, this can be the result of a maths operation, or the value contained in another variable:

// MaxHealth is 2.5
float MaxHealth { 5.0 / 2.0 };

// CurrentHealth is 2.5
float CurrentHealth { MaxHealth };

Remember, the expression is calculated before the variable type is considered.

In the below example, we perform integer division to yield 5 / 2 = 2. We then assign the integer 2 to the float Health, which will convert it to the floating point number 2.0

float Health { 5/2 }; // Health is 2.0

Floating Point Operations

All the operators we've seen for integers are also available to floating point numbers.

float Health { 5.0 }; // Health is 5.0
Health = Health + 20.0; // Health is now 25.0
Health++; // Health is now 26.0
Health--; // Health is now 25.0

// We can freely combine floating and
// integer numbers in the expressions
Health += 25; // Health is now 50.0
Health -= 10; // Health is now 40.0
Health *= 2.5; // Health is now 100.0
Health /= 3; // Health is now 33.3333...

Summary

In this lesson, we journeyed through the fundamentals of numeric variables in C++, covering key concepts:

  • Variable Creation and Types: We revisited creating variables in C++, emphasizing the addition of the float type for numbers with decimal points.
  • Numeric Operations and Syntax: Explored arithmetic operations (+, -, *, /) and their use.
  • Thousand Separators: Introduced the use of single quotes as thousand separators for readability in large numbers.
  • Increment and Decrement Operators: Learned about shorthand operators (++, --) and their significance in simplifying code.
  • Compound Assignments: Discussed compound assignment operators (+=, -=, *=, /=) for efficient value manipulation.
  • Understanding Integer and Floating-Point Division: Addressed how C++ handles division, especially the distinction between integer and floating-point division.
Next Lesson
Lesson 5 of 60

Booleans - true and false values

An overview of the fundamental true or false data type, how we can create them, and how we can combine them.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Division by Zero in C++
What happens if I divide by zero in my code? Will it crash my program or give me an error?
Pre vs Post Increment
Why does Level++ and ++Level do the same thing? When should I use one over the other?
Rounding Floating Point Numbers
How do I round floating point numbers to the nearest integer? For example, if I want 2.7 to become 3?
Integer Overflow in C++
What happens if I try to store a really big number like 999,999,999,999 in an int? Will it give me an error?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant