Remember Values
Declare and use int, double, and char variables.
You now know how to print to the screen and perform basic math with C++. Now, let’s give your program a memory. In this lesson, you’ll learn how to create variables— containers for numbers, letters, or anything your program needs to remember.
Goal
You’ll aim to:
Declare variables using C++ types.
Store and reuse values.
Understand type basics:
int
,double
,char
.
Make a variable
To declare a variable in C++, we use the following simple syntax:
Now, let’s use this syntax in the code below to declare and use a variable of integer (int
) data type:
#include <iostream>using namespace std;int main() {int score = 100; // Stores 100 in 'score'cout << "Score: " << score << endl; // Prints the value of score (100) with label (Score: )return 0;}
Here is a visual representation of our variable, score
:
More types
Here are some additional data types we can use for our variables, depending on the type of value they will hold:
#include <iostream>using namespace std;int main() {double price = 4.99; // Decimal numberchar grade = 'A'; // Single charactercout << "Price: $" << price << endl;cout << "Grade: " << grade << endl;return 0;}
You’ve used three core types.
Store the result in a variable
We have already done some math with C++. Now, let’s store the result of our calculation in a variable:
#include <iostream>using namespace std;int main() {int total = 8 + 12; // Creates an integer variable named total and stores the result of 8 + 12 in itcout << "Total: " << total << endl; // Prints the text "Total: " followed by the value of total, then moves to a new linereturn 0;}
Now your math lives inside a named value.
Change a variable
We don’t just declare a variable and use it unchanged throughout our program; the value a variable holds can be changed or updated (hence the name ‘variable
’):
#include <iostream>using namespace std;int main() {int age = 18; // Stores 18 in ageage = age + 1; // Increases age by 1cout << "Next year: " << age << endl; // Prints updated age with labelreturn 0;}
You have updated and reused a variable.
Quick type reference
int
→ whole numbersdouble
→ decimals/floating pointchar
→ single letters or characters
Mini challenge
Create a small program with the following:
Your name (each alphabet as
char
)Your age (as
int
)Your height (as
double
)Print a sentence using all three.
#include <iostream>using namespace std;int main() {// Your code goes herereturn 0;}
If you’re stuck, click the “Show Solution” button.
We declared individual char
variables for each letter of the name. Now, imagine a name that’s 15 characters long—or a sentence with over 100 characters. Would we declare 100+ char
variables in that case?
What’s next?
You’ve learned to remember numbers. Now let’s level up and work with words using strings!