Mark As Completed Discussion

Data Types

In C++, data types determine the kind of data that a variable can hold. There are several built-in data types available in C++. Here are a few common ones:

  • int: used to store integer values, such as 5 and -12
  • double: used to store floating-point values, such as 3.14 and 2.718
  • char: used to store single characters, such as 'A' and 'b'

It is important to use the appropriate data type for the value you want to store, as different data types have different memory requirements and capabilities.

Variable Declarations

To declare a variable in C++, you need to specify its data type and give it a name. Here is the syntax for variable declaration:

SNIPPET
1<data_type> <variable_name>;

For example, to declare an integer variable named age, you can use the following code:

SNIPPET
1int age;

You can also initialize a variable at the time of declaration by assigning a value to it. Here is an example:

SNIPPET
1int age = 30;

The above code declares an integer variable named age and initializes it with the value 30.

Example

Let's look at an example that demonstrates the use of different data types and variable declarations in C++:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5  int age = 30;
6  double height = 1.75;
7  char grade = 'A';
8
9  cout << "My age is " << age << endl;
10  cout << "My height is " << height << " meters" << endl;
11  cout << "My grade is " << grade << endl;
12
13  return 0;
14}

This code declares three variables: age of type int with a value of 30, height of type double with a value of 1.75, and grade of type char with a value of 'A'. It then outputs the values of these variables to the console.

Try running the above code to see the output.

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