SrcForge

Lesson 3

Variables

How to declare, initialize, and use variables in C++ with beginner-friendly examples.

Lesson content

Variables in C++ are used to store data that can change during program execution. Learning how to declare and use variables is one of the most important beginner concepts in C++ programming.

What Are Variables in C++?

A variable is a named memory location used to store data in a program. In C++, variables must be declared before they are used, and each variable must have a data type.

Variable Declaration in C++

DataType variable = value;

Example 1: Basic Variable Declaration and Initialization

#include <iostream>

using namespace std;

int main() {
  int age = 25;
  double price = 19.99;
  cout << "Age: " << age << endl;
  cout << "Price: " << price << endl;
  return 0;
}

Example 2: Using Variables in Calculations

#include <iostream>

using namespace std;

int main() {
  int length = 10;
  int width = 5;
  int area = length * width;
  cout << "Area: " << area << endl;
  return 0;
}

Common Data Types Used with Variables

  • int — Stores whole numbers. Example: int age = 25;
  • double — Stores decimal numbers. Example: double price = 19.99;
  • char — Stores a single character. Example: char grade = 'A';
  • string — Stores text. Example: string name = "John";
  • bool — Stores true or false values. Example: bool isPassed = true;