Data Types
Data Types
Basic Data Types
Char
Let's start with a type called char.
The char data type represents a single character. The character is enclosed in single quotes. For example 'A' or 'B' and so on.
To declare a variable of type char, simply use the char keyword.
In this example, we declare a variable of type char named grade, which means grade in English, and assign it the value 'A'. Note that char can contain any single character, including letters, digits, and special characters such as '.' or '?'. As a result, we now have a char with a value of 'A', and we output it to the screen, saying that, for example, some student received a grade 'A'.
ASCII Encoding
ASCII is a character encoding standard that assigns a unique numeric value to each character. In C++, you can get the ASCII value of a character using casting. For example:
In this example, we cast -- try to convert the character 'A' to a number that has the corresponding ASCII value, which is then stored in the asciiValue variable.
Let's try to output the ASCII value:
When this program runs, it will display: 65
String
Next, we will look at a second type called string that represents strings. A string is a sequence of characters we are already familiar with and is used to represent textual data. You can think of a string as a set of characters enclosed in double quotes.
You can declare a variable of type string using the string keyword from the string library.
In this example, we declare a variable of type string named greeting and assign it the value "Hello World!". The string type allows you to perform various operations on strings.
Now let's try to output the string "Hello World!" that we created to the screen.
Float and Double
Now let's remember int, which we are already familiar with. If we recall int, its problem was that it only handles integers. The question arises - what if we need to work with non-integer numbers?
For this, let's look at floating-point data types: float (floating-point numbers - numbers that have a certain precision) and double (floating-point number with increased precision).
In this example, we declare a variable of type float named pi and assign it the value 3.14159. We also declare a variable of type double named gravity and assign it the value 9.8. The main difference between and types lies in their precision. has higher precision and can store larger numbers compared to . Therefore, if you're working with large numbers, it's better to use . If you're working with small numbers, you can use . In most cases, it's preferable to use .