- C++ Introduction
- C++ Getting Started
- C++ Syntax
- C++ Output (Print Text)
- C++ Comments
- C++ Variables
- C++ Declare Multiple Variables
- C++ Identifiers
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ Conditions
- C++ Switch
- C++ While Loop
- C++ For Loop
- C++ Break And Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Function Overloading
- C++ OOP
- C++ Classes And Objects
- C++ Class Methods
- C++ Constructors
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Multilevel Inheritance
- C++ Multiple Inheritance
- C++ Inheritance Access
- C++ Polymorphism
- C++ Files
- C++ Exceptions
- C++ How To Add Two Numbers
C++ Variables
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords), for example:
int
- stores integers (whole numbers), without decimals, such as 123 or -123double
- stores floating point numbers, with decimals, such as 19.99 or -19.99char
- stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotesstring
- stores text, such as "Hello World". String values are surrounded by double quotesbool
- stores values with two states: true or false
Practice Excercise Practice now
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:
Syntax
Where type is one of C++ types (such as int
), and variable is the name of the variable (such as x or myName). The equal sign is used to assign values to the variable.
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int
and assign it the value 15:
cout << myNum;
You can also declare a variable without assigning the value, and assign the value later:
Example
myNum = 15;
cout << myNum;
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Example
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10
Practice Excercise Practice now
Other Types
A demonstration of other data types:
Example
double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)
Practice Excercise Practice now
Display Variables
The cout
object is used together with the <<
operator to display variables.
To combine both text and a variable, separate them with the <<
operator:
Example
cout << "I am " << myAge << " years old.";
Practice Excercise Practice now
Add Variables Together
To add a variable to another variable, you can use the +
operator:
Example
int y = 6;
int sum = x + y;
cout << sum;
Practice Excercise Practice now
Products
Partner
Copyright © RVR Innovations LLP 2024 | All rights reserved - Mytat.co is the venture of RVR Innovations LLP