Thuta Learning
BasicProgrammingbeginner

Variables

Relax. We'll talk through this in plain words — no textbook voice.

You can think of a variable as a little box that stores a value in your program. C++ is a statically typed language, so you have to declare a variable's data type before you use it. For example, int age tells the compiler upfront that age will only ever store an integer value.

cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
    int age = 20;
    double height = 5.8;
    char grade = 'A';
    string name = "Thuta";
    bool isLearning = true;

    cout << name << " is " << age << " years old." << endl;
    cout << "Height: " << height << endl;
    cout << "Grade: " << grade << endl;
    cout << "Learning C++: " << isLearning;
    return 0;
}

This example stores five variables with different data types. Since it uses string, it includes #include <string>. In cout, << lets you chain together text and variable values in the output.

You should see
Thuta is 20 years old. Height: 5.8 Grade: A Learning C++: 1

Info

bool values printed with cout show up by default as 1 or 0. true is 1, and false is 0.

Easy traps

  • Watch out for using string without including it, writing a character with double quotes instead of single quotes, and putting a numeric value inside text quotes when you actually want to calculate with it.
Variables | Thuta Learning