Mark As Completed Discussion

Data Types and Variables

In C++, variables are used to store and manipulate data. Before we can start using variables, we need to understand the different data types available in C++.

Primitive Data Types

C++ provides several primitive data types, each with its own characteristics and range of values. Here are some of the commonly used primitive data types:

  • int: Used to store integer values
  • float: Used to store floating-point numbers
  • char: Used to store single characters
  • bool: Used to store boolean values (either true or false)

Variable Declaration and Initialization

To declare a variable, we specify its data type and give it a name. We can also initialize the variable with a value.

For example, let's declare and initialize variables of different data types:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5  // Variable declaration and initialization
6  int age = 25;
7  float weight = 65.5;
8  char gender = 'M';
9  bool isStudent = true;
10
11  // Printing variables
12  cout << "Age: " << age << endl;
13  cout << "Weight: " << weight << endl;
14  cout << "Gender: " << gender << endl;
15  cout << "Is student: " << isStudent << endl;
16
17  return 0;
18}

In the code above, we declare variables age (an int), weight (a float), gender (a char), and isStudent (a bool). We then assign values to these variables and print their values using the cout object.

Feel free to modify the code and experiment with different values and data types. Running the code will help deepen your understanding of variables and data types in C++.

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