C++ Variables

Variables act as containers that store data in a program. They allow you to save, modify, and manipulate information while writing efficient code.

Tutorials dojo strip



Different Types of Variables

C++ provides several data types, each designed for storing specific types of values:

  • int → Stores whole numbers without decimals (e.g., 120, -45)
  • double → Holds floating-point numbers (e.g., 25.75, -8.99)
  • char → Stores single characters (e.g., 'M', 'B') within single quotes
  • string → Holds text (e.g., "Harley Davidson", "Ducati") within double quotes
  • bool → Holds true/false values, useful for logical decisions




Declaring and Assigning Variables

To define a variable, specify its type and give it a value:

Syntax:

C++
  • type → Defines what kind of data the variable holds (int, double, etc.)
  • variableName → The name assigned to the variable
  • = → Used to assign a value to the variable


Storing a Number

C++


Declaring a Variable Without Assigning a Value

C++




Modifying a Variable

Once assigned, a variable can change its value during execution.

Example: Updating a Variable

C++




Other Variable Types

C++ offers multiple data types to handle different kinds of values:

C++




Displaying Variables in Output

To print a variable along with text, use the cout object with the << operator:

C++




Adding Variables Together

You can perform calculations using multiple variables.

Example: Addition

C++

Output: 270

Tutorials dojo strip