Data Types
In C++ every variable must have a specified data type. The data type determines:
- What values the variable can contain
- How much memory the variable takes up
- What operations we can perform with the variable
Basic data types in C++:
int number = 42; // Whole numbers (-2147483648 to 2147483647)
double decimal = 3.14; // Decimal numbers (precision ~15 decimal places)
float smallerDecimal = 3.14f; // Decimal numbers (precision ~7 decimal places)
char character = 'A'; // One character (letter, number or symbol)
bool truth = true; // Boolean value (true or false)
string text = "Hello"; // Text (requires #include <string>)
Examples of values for different types:
int
: 42, -17, 0, 1234double
: 3.14, -0.001, 12345.6789float
: 3.14, -0.001, 12345.6char
: 'A', '1', '$', ' 'bool
: true, falsestring
: "Hello", "12345", "C++"
Using the wrong type can lead to errors or data loss:
int x = 3.14; // x will be 3 (decimal part is lost)
char y = "A"; // Error! For character use single quotes 'A'
Instructions
Declare and initialize the following variables with correct data types:
age
with value25
(whole number)height
with value175.5
(decimal number)letter
with value'A'
(one character)isStudent
with valuetrue
(boolean value)
Start programming for free
5/6