Menu
Coddy logo textTech

Whole Numbers

Part of the Fundamentals section of Coddy's C++ journey — lesson 5 of 74.

Variables are containers that hold data values. They are used to store, manipulate, and display information within a program.

In short, a variable is like a memory unit that we can access by typing the name of the variable. 

Each variable has a unique name and a value that can be of different types. C++ has various built-in data types that define the type of value a variable can hold.

Working with variables involves two steps:

  • Declaration — telling the computer that the variable exists:
    int age;
  • Initialization — assigning the variable a value:
    age = 30;

These two steps can be combined into one line using the following format:

variable_type variable_name = value;

In C++, whole numbers are typically represented using the int data type.

int is used to store whole numbers without any decimal point. For example:

int age = 30;
int temperature = -5;
int count = 100;

When declaring variables in C++, you need to specify the type of the variable before the variable name. This is known as type declaration. Once a variable is declared with a certain type, it can only hold values of that type.

You can also declare multiple variables of the same type in a single line:

int a, b, c;

In modern C++, variables can also be initialized using brace initialization or constructor initialization:

int num{0};   // brace initialization
int num(0);   // constructor initialization

C++ also provides the auto keyword, which lets the compiler automatically deduce the type of a variable from its assigned value:

auto score = 10;    // deduced as int
auto price = 9.99;  // deduced as double
challenge icon

Challenge

Beginner

Declare an int variable named quantity and initialize it with the value 5.

Cheat sheet

Variables store data values. Declare and initialize using:

variable_type variable_name = value;

Use int for whole numbers:

int age = 30;
int temperature = -5;

Multiple variables of the same type can be declared in one line:

int a, b, c;

Alternative initialization styles:

int num{0};   // brace initialization
int num(0);   // constructor initialization

Use auto to let the compiler deduce the type automatically:

auto score = 10;    // deduced as int
auto price = 9.99;  // deduced as double

Try it yourself

#include <iostream>

int main() {
    // Declare and initialize variables here
    
    
    // Output the values - Don't change below this line
    std::cout << "Quantity: " << quantity;
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals