Next topic, which is included in the basic programming – is data types, variables and constants. Almost always the first topic in the study of any course – this is theory and boring things. So is folded, What to start writing more or less interesting programs, we need to learn some basics and gain basic knowledge. I, of course, will try to keep it short and so reveal the topic of the article, but be patient. In this article we will look at the same time, what is the data type, and why we need them in programming, as well as learn about the variables and constants.
Data types. First answer “what for” exist data types. Look, let's say we need to write a program, which displays the data about age, weight and height of the individual. But, so the program can access these data, they should be stored somewhere in the computer's RAM, and only then “ask” show them. For this we needed the data types – for compiler “understand” how much memory should be allocated for the data, and that memory will be stored (integer (age), real (weight and height), symbols, etc.).
Data types can be divided into three groups: numeric, symbolic and logical. To indicate the data types used special reserved (key) words. Below, we shall consider them and indicate how much memory and what kind of data is allocated to them, they can store.
Numeric data types: to store integers (0, 33, -27 etc.)
int (4 bytes) – stores the numbers between -2 147 483 648 to 2 147 483 647
short (2 bytes) – stores the numbers between -32 768 to 32 767
long (4 bytes) – stores the numbers between -2 147 483 648 to 2 147 483 647
Numeric data types: дTo store real numbers (floating point: –435.332, 54.77, 3.0)
float (4 bytes) – keeps fractional number up to 7 digits after decimal point
double (8 bytes) – keeps fractional number up to 15 digits after decimal point
Символьный тип: дTo store one character
char (1 bytes) – stores one symbol. For example: 'f', ‘+’ or '4’ (as a symbol). Single quotes are required.
It isn't data type to store strings in C++. Later we will get know you so, how to store strings in memory.
bool (1 bytes) – mcan take only two values true (truth) and false (lie)
Immediately you should pay attention, that all reserved words under data types are written not in capital, but lowercase (small) letters. If you declare type bool, as Bool – the compiler generates an error message. In the editor, when writing code, all keywords of C++ are highlighted in blue (this applies to all reserved words). So if you enter type, and word was not blue – check the spelling.
Variables and constants. Their names speak for themselves. And variable and constant – this specific area in RAM, which have a name (programmer gives name ). Only a variable can change their value during the execution of the program, constant is determined once and can not be changed.
Time, for example, this is variable. Now, let's say, 3 hours of the day, and through 2 hours will already be 5 pm. But the number of hours in the day – this is already a constant.
And the variables and constants of the declaration should definitely give a name. There are strict rules, according to which the given names:
- variable name can contain large and small letters of the English alphabet, digits, and ‘_’ (underscore). With underscores the names of a lot easier to read. Compare amountofapples and amount_of_apples.
- name can not start with a digit! amount_of_apples1 – шt is possible, 1amount_of_apples – not allowed ))
- name cannot be a reserved word (int, bool …). If you come up with the name of the variable, entered, and it will highlight in blue, it means a word is a reserved in C++. Come up with a new name.
- variable name should be meaningful (logical volume, that will store the variable). That is. hardly anyone would guess, that in variable x stored value amount of apples. It is more logical to call such a variable amount_of_apples.
Declare and initialize variables and constants.
How can we create a variable and specify what value it will store? To do this, we must first specify datatype, then give the name of the variable (adhering to the rules discussed above), put a sign = (means assign) and specify a value. For example, create a variable, which will store the value of the quantity of apples: int amount_of_apples = 7;.
Assigning a value to a variable when it is called creation initializing. It is advisable to always initialize variables when creating, even if you don't know what value the variable will take during the work programme. In this case, initialize its zero: int amount_of_apples = 0;. The thing is, that there is no free memory. And if you just created a variable int amount_of_apples; and not assigned any value to it, it will still keep some residual data from previous programs. Therefore,, although it is not an error, first declare a variable, and assign a value below, it is desirable to assign a value to this variable directly , thereby clearing it from “garbage”. By the way, in MVS 2013, if you try to display the value of a variable is not initialized, the compiler will generate an error.
Regarding the constants, the value must be set to immediately when you create. For example, we define a constant, which will store the number of days in a week: const int daysInWeek = 7; To make it clear to the compiler, that it is a constant, instead of the usual variable, before a data type must use the keyword const.
So, perhaps, proceed to consider several examples, to understand and remember the, what we're talking. Do not forget, dialing code – practice.
// Задача: Есть 2 сумки. В одной 11 яблок, во второй 44
// Создать переменные, которые будут хранить количество яблок в сумках
// и одну переменную, в которую надо записать общее количество яблок.
using namespace std;
//создание переменных и инициализация
int amount_of_apples1 = 11;
int amount_of_apples2 = 44;
int inBox = 0; // для записи общего количества
cout << "В пустой коробке - " << inBox << endl;
// вывод данных на экран
cout << "В первой сумке - " << amount_of_apples1 << endl;
cout << "Во второй сумке - " << amount_of_apples2 << endl;
cout << endl; // еще один перевод на новую строку
// подсчет общего количества яблок в коробке
inBox = amount_of_apples1 + amount_of_apples2;
// показ общего количества на экран
cout << "Всего в коробку добавлено " << inBox << " яблок" << endl;
In string 15 variable inBox set to the value 0, since we do not know what value to be written. In line 17, we show the initial value on the screen. As you can see, to show the value of the variable on the screen, enough to refer to it by name: cout << inBox; Note, how it works cout. Using the operator << , we can alternate the display of text and display the variable value. So we did in rows 17, 19, 20 and 27. In string 24 in inBox variable amount of recorded variables: amount_of_apples1 + amount_of_apples2. I.e, the compiler, first add up the values of these variables, and then write the sum in inBox . And to make sure, that all are counted and recorded – again display the value inBox the screen – string 27. Run the program (first, Ctrl + Shift + B, if there are no errors the next Ctrl + F5 details here). That's what we see:
В пустой коробке - 0
В первой сумке - 11
Во второй сумке - 44
Всего в коробку добавлено 55 яблок
Select main, it is necessary to remember:
- data type is specified before the variable name and determines what data will be stored (number, symbol… ) and how much memory you want to allocate for them.
- programmer gives the name to a variable , observing certain rules (listed above).
- to create (declare) a variable you must specify its type and give a name. It is advisable to immediately initialize variable (assign a value when creating): type name = value;
- to declare a constant, you must use the keyword const and necessarily just assign a value: const type name = value;
- You can assign variables not only a certain value, and the result of the calculation: amount_of_apples1 = amount_of_apples2 + 33;
- it is desirable to declare variables at the beginning of main-function. And even if necessary leave a comment, what they will keep.
- name is case-sensitive. Names Apple and apple represent different variables.
Do you want to spend more time training – check out the video tutorials!
Constants described in this video:
If you have questions or something went wrong, please comment. Be sure to consider additional tasks and solutions on this topic.
|Newsletter of programming: