What are Variables?
Variables are like containers that store data in your program. Think of them as labeled boxes where you can put different types of information.
In C++, you need to tell the computer what type of data you want to store. Here are the most common types:
int
- for whole numbers (like 1, 42, -7)
double
- for decimal numbers (like 3.14, 2.5)
std::string
- for text (like "Hello", "Player Name")
To create a variable, you write: type name = value;
int age = 25;
double price = 19.99;
std::string name = "Alex";
Your First Task
Declare an integer variable named playerHealth
and initialize it with a value of 100
.
Working with Different Types
Great! Now let's work with decimal numbers. A double
can store numbers with decimal points.
This is perfect for things like prices, measurements, or any value that needs precision.
Your Task
Declare a double
variable named itemPrice
and initialize it with a value of 19.95
.
Storing Text
Now let's work with text! In C++, we use std::string
to store text.
Text values must be enclosed in double quotes: "Your text here"
Your Task
Declare a std::string
variable named playerName
and initialize it with your name (or any name you like).
Displaying Variables
Perfect! Now let's see how to display the values stored in our variables.
You can use std::cout
to print variables, just like we did with text.
Your Task
Un-comment the three lines below to print all your variables to the console.