Numbers and Literals

An introduction to the different types of numbers in C++, and how we can do basic math operations on them.
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, Unlimited Access
3D art of a boy using an abacus
Ryan McCombe
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 };

Thousand Separators

When dealing with large numbers, it is often helpful to add separators to make them more readable for humans. For example, we often add commas to a number like 100,000,000.

We can do something similar in our code if we want. In C++, we can not use commas for this purpose - instead, we can use the single quote character: '

int LargeNumber { 100'000'000 };

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

The Assignment Operator (=)

A statement like Level = Level + 1 may seem weird if we interpret it as an equation.

But in C++, and most programming languages, the = symbol is an operator. It does not specify an equation - instead, like any operator, it acts upon its operands.

= is often referred to as the assignment operator. It updates the value of its left operand (Level, in this case) with the value of its right operand (Level + 1, in this case).

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.

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 implementing 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

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. We’ll discuss what "unary" means later in the course.

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 5/2 expression 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 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.

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...

Preview: Float Literals

In other learning resources, you may see float variables used with an f suffix, as in 3.14f. For example, the following two variable initializations are equivalent:

float VariableA { 3.14 };
float VariableB { 3.14f };

We won’t use the f suffix in this course, and will explain what it means in more detail later in this chapter.

The Floating Component is Optional

Often, we will be using float and double literals that are initially "round", eg, 4.0 and 5.0.

Where the floating component is 0, it can be removed entirely from the literal. This is shown below, where both variables will have the value 4.0:

float VariableA { 4. };
float VariableB { 4.f };

We don't do this in our code samples, but it's worth mentioning, as this often causes some confusion when looking at other people's code.

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.
  • Negative Numbers and Different Integer Types: Discussed the use of negative numbers and explored various integer types available in C++.
  • Signed vs. Unsigned Integers: Examined the concept of signed and unsigned integers and their implications.
  • Overflows and Memory Considerations: Highlighted the potential issues with overflows in numeric operations.

Preview of the Next Lesson: Boolean Variables

In our next lesson, we'll shift our focus to another fundamental aspect of programming: Boolean variables. This upcoming session will include:

  • Introduction to Boolean Logic: Understanding the true/false nature of Boolean variables.
  • Using Booleans in Conditional Statements: Learn how to use Boolean variables in decision-making processes within your code.
  • Boolean Operators: We'll explore logical operators (AND, OR, NOT) and how they are used to form complex logical expressions.
  • Practical Applications of Booleans: Discover how Boolean variables are integral in control structures such as loops and conditional statements.

Was this lesson useful?

Next Lesson

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.
3D art of a wizard character
Ryan McCombe
Ryan McCombe
Updated
3D art showing a progammer setting up a development environment
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, Unlimited Access
Types and Variables
3D art showing a progammer setting up a development environment
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access

This course includes:

  • 60 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Next Lesson

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.
3D art of a wizard character
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved