Mark As Completed Discussion

Variables and Data Types

In C++, a variable is a named container that stores a value of a specific data type. Data types define the kind of values that variables can hold.

When declaring a variable, we specify the variable's data type, followed by the variable's name.

For example:

SNIPPET
1int age;

In the above example, we declare a variable named age of type int, which can hold positive or negative whole numbers.

C++ provides several built-in data types, including:

  • int - for integers
  • float - for floating-point numbers
  • char - for single characters
  • string - for sequences of characters
  • bool - for boolean values (true or false)

Here's an example that demonstrates declaring variables of different data types and outputting their values:

SNIPPET
1#include <iostream>
2
3using namespace std;
4
5int main() {
6    // Declare variables
7    int age = 25;
8    float height = 6.2;
9    char gender = 'M';
10    string name = "John Doe";
11    bool isEmployed = true;
12
13    // Output variables
14    cout << "Name: " << name << endl;
15    cout << "Age: " << age << endl;
16    cout << "Height: " << height << " feet" << endl;
17    cout << "Gender: " << gender << endl;
18    cout << "Employed: " << boolalpha << isEmployed << endl;
19
20    return 0;
21}

This code declares variables age, height, gender, name, and isEmployed. It assigns values to these variables and then outputs their values using the cout object.

When running the code, the output will be:

SNIPPET
1Name: John Doe
2Age: 25
3Height: 6.2 feet
4Gender: M
5Employed: true

By understanding how to declare variables and the different data types in C++, you are equipped with the basic knowledge to start working with data in C++. This is an important foundation for learning more advanced concepts in programming and applying them in finance.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment