Tutorial How to start programming in C++ (Part 3 of 5)

Start programming in C++ . Do you think this tutorial is useful?

  • Yes, of course!

    Votes: 12 85.7%
  • No, I don't like it!

    Votes: 2 14.3%

  • Total voters
    14
  • Poll closed .

JM Security

Level 30
Trusted
Joined
Apr 12, 2015
Messages
1,904
#1
Hello guys!

This is the third part of this C++ tutorial, and I'm going to explain other concepts about this important programming language.

Previous article here: [Tutorial] How to start programming in C++ (Part 2)

Let's start!


Autoincrement operator and dual operators

The C++ language has a special operator to increment a variable by one. To write:

n ++;



is equivalent to write:

n = n + 1;



that is, to increase the value of the variable n. The + operator + is the increment operator. The mutual-operator-(two less) decrements the value of a variable:

m--; reduces the value of 1



The operator -- is the operator of the autodecrease. Increment operator operators and autodecrease are used in these counters.

Even for accumulators are foreseen in the C++ language special operators (operators).

x + = 37;



K1 + = k2;



a + = (b/2);

the use of double operator + = makes the equivalent expressions respectively to:

x = x + 37;



K1 = k1 + k2;



a = a + (b/2);

The two expressions are equivalent, from the point of view of the final result, only double operator usage increases the readability of assignment: becomes much clearer that this is an upgrade and not assigned a new value, as might be expected from the use of the symbol =.

In the double operator you can use all arithmetic operators.

Later in these notes you'll agree, as common, use:

increment operator operators and autodecrease whenever a variable must be updated with the unit

Double operator (eg. + =-= etc.) whenever it is called a generic update to a variable (for example in batteries)

the assignment operator (i.e. =) in all other cases.

Pre and post increment


To increment by 1 the variable z can be written in two ways:

z ++;



++ z;

that is, putting the operator ++ before or after the variable name.

In this case, the two forms are equivalent. The difference only matters when you write an expression that contains z ++ or ++ z.

Writing z ++, the present value of z is first used then incremented:

int x, z; two integer variables

z = 4; the value of z is 4

x = z ++; even x is 4 but z is worth 5



Writing ++ z, the present value of z is first increased and then used:

int x, z; two integer variables

z = 4; z is 4

x = ++ z; now x is 5 as z



Ultimately, just keep in mind that the order of operations, in the expression after the assignment, occurs from left to right.

Loops and while construct

Cyclic structures assume a key role in designing programs, not least for the fact that, by using these structures, you can instruct the computer to perform repetitive tasks on different sets of data: that is, all in all, the fundamental role of computer systems.

It is because of the above considerations that the programming languages provide the programmer with various types of cycles in order to adapt more easily to the different needs of designing programs. The more general construct is the loop while (iterative cycle with on top):

While (esp)

instruction



If it is verified that esp is real, in which case it executes the statement. The cycle repeats while esp turns out to be true.

Of course, as observed before, education can be a block and, again, it may be useful to enclose the statement in a block even if it is only one.

As an example of instructions treated up to this point, there is a program that, given a sequence of positive integers, provides the amount of even numbers in the sequence and their sum. Any negative number, or zero, stop processing.

#include <iostream>

using namespace std;



int main ()

{

int vn,//value in the sequence being processed

count, sum; count and sum even numbers



initializing accumulators



cout < < "count and sum of pari\n\n";

count = sum = 0; /*1*/



examination of the numbers



"enter positive number"; < < cout

CIN >> vn; /*2*/



While (vn > 0) {



check if input number equal



If (! ( VN% 2)) {/* 3 */

count ++; /*4*/

sum + = vn; /*4*/

}



next issue to be processed



"enter positive number"; < < cout

CIN >> vn;

}



processing results



cout < < "in the sequence there were"

"even numbers" counts < < < < < < endl;

cout < < "their sum is" < < sum < < endl;



return 0;

}



In 1 you initialize to zero the counter and accumulator of peers.

In 2 it acquires the first numeric value to process.

3 control allows you to determine whether the number is introduced. The modulo operator% is used to compute the remainder of integer division between vn and 2 and checks whether the rest is null so that, at 4, you can update the counter and accumulator.

Loops and for construct

The for statement is used traditionally to encode cycles to counter cyclical instructions that need to be repeated a number of times.

The format of the for construct is as follows:

for (Exp1; esp2; esp3)

instruction



The cycle begins with the execution of Exp1 (loop initialization) which will no longer run. Then it examines esp2 (loop control condition). If EXP2 is true, statement is executed, otherwise the loop is not path even once. Finished executing statement runs esp3 (update) and again evaluated esp2 that if is true gives rise to a new run. The process repeats until esp2 turns out to be false.

Knowing the amount of numerical values to be processed, the previous program of processing even numbers in a sequence, might be encoded:

#include <iostream>

using namespace std;



int main ()

{

int vn,//value in the sequence being processed

count, sum; count and sum even numbers

int qn,//quantity numbers to be processed

I; /*1*/



initializing accumulators



cout < < "count and sum of even numbers\n\n";

cout < < "how many numbers must be processed?";

CIN >> qn; /*2*/



count = sum = 0;



examination of the numbers



for (i = 0; i < qn; i ++) {/* 3 */



"enter positive number"; < < cout

CIN >> vn;



check if input number equal



If (! ( VN% 2)) {

count ++;

sum + = vn;

}

}



processing results



cout < < "in the sequence there were"

"even numbers" counts < < < < < < endl;

cout < < "their sum is" < < sum < < endl;



return 0;

}



Two new variables are added in 1 for the amount of numbers to be processed and the loop counter.

Is made in 2 input the quantity of numbers to process that, with the cycle that starts at 3, are processed.

The program will first assign the value 0 to the variable i (the first expression of the for), it checks whether the value of i is less than qn (the second expression) and because the expression holds true will execute the instructions included in the loop. After the statements that make up the cycle you are upgrading the as is apparent from the third expression for, repeats the content control in the second expression and continue as before until the value doesn't make a false condition.

The loop executes qn times and the counter values 0, 1, 2, ..., (qn-1). You could initialize the counter at 1 and end the loop with control, but this is the preferred < = qn adopt a Convention, common in computer applications, start the counts from the value 0.


This way of acting of the for loop is that common to all cycles (cycles per meter) provided by compilers for different programming languages. The C++ language, considering the three parts of the construct as generic expressions, expands the potential for plenty, generalises and so as to include, for example, as a special case the while loop. The first version of the program (one that uses the loop), the piece of code that includes the processing cycle, might be coded:

...

for (count = 0; 0;) {sum = vn >



check if input number, equal



If (! ( VN% 2)) {

count ++;

sum + = vn;

}



next issue to be processed



"enter positive number"; < < cout

CIN >> vn;

}

...



The loop executes zero count and sum (which will run once) and immediately after checking if vn is positive and, in this case, you will follow these instructions. After the instructions, missing the third expression of the for, is only repeated control over vn.

Initializations of counts and sums could be worked out for, in which case it would be lacking the first expression.

Do-while loops and construct

The use of the while statement provides the test about the condition at the beginning of the cycle. This means that if, for example, the condition is found to be false, the statements that are part of the cycle would jump and would not run even once.

When the statement included in the loop should be executed at least once, it may be more convenient to use the construct:

do

instruction

While (expr);



In this case runs education and subsequently checked if expr is true, in which case the cycle repeats.

As always the iteration may include a compound statement.

It is good to point out once again that in a block for, while or do ... while loop, as well as in the if block, there may be any number of statements of all kinds including other blocks for, while or do ... while loop. Loops may be nested.

Software Engineering: the writing style

A key point in writing a program is the coding style. Follow the rules for writing the program facilitates the understanding and care and also, ultimately, scripture itself. The software maintenance for the correction of errors encountered during use, for adding new features for editing functionality and maintenance costs may be higher development costs. A good writing style of the programs is an integral part of the documentation and programs need to be understood.

The examples in these notes are written according to some basic rules, to use universal now, according to the style used by Bell Laboratories.

A good writing style using blank lines and comments to make the code more clear and easy to understand. The commentary explains in brief what the lines of code that follow it. Each new block which has a new feature or that processes a given intermediate goes preceded by an explanatory comment. Each comment line is preceded and followed by a blank line to make it more discoverable. Similarly, each control structure (if, while or for).

A variable has a mnemonic name reminiscent of its use in order to facilitate the understanding of the code.

The use of proper indentation (tailback of lines of code) is of fundamental importance not only for the understanding of the code but also to avoid common mistakes. The examples in these notes is used an indentation of 2 characters. To summarize the rules for the tailback of the lines of code:

every line of code is generally aligned with the above line

If in the previous row is an open brace, the line should be indented to the right of many spaces as you are chosen for the indentation. In examples 2 spaces

the beginning of the line moves to the left when you have to close a block: you must enter a locked brace or writing the next statement after the only statement included in a conditional structure or cycle.

The use of proper indentation allows avoiding frequent errors of omission closure (closed brace) of a structure, especially when there are multiple nested structures (one inside the other).

Conventions for the use of braces and indentation of code can be summarized as follows:

int main ()

{

program code

}



the parentheses around the main occupy a line by each.

While (...) {

code in the loop

}

code outside the loop



the block that contains the code in a loop (while or for) cyclical education line begins and ends with the parentheses that occupies a row alone.

If (...) {

code for true condition

}

else {

code for condition false

}

other code



If the conditional structure is missing the lock for the condition false, you are encoding as the cyclic structure. If any block for false condition that should be treated as if it were a separate structure.

In summary the coding structure, if this involves a block of code, provides the opening parenthesis in the same line of code to the beginning of the structure and the closing parenthesis alone on a line. The rows that contain the instructions that depend on the structure must be indented because in this way, visually, it becomes clear the dependency.

From the algorithm to the code: step-by-step procedure

To summarize what has been said in this part sets out the encoding of the algorithm, already developed to calculate the total amount of an invoice unit price of items sold and knowing every object in each row that compose it. Now, however, you will see the proceedings to obtain the complete programme starting from the definition of the problem.

As a first step you can encode the overall program structure with variable declaration:

#include <iostream>

using namespace std;



int main ()

{

int qven, pzun; q. sold, unit price single sale

int totf; total invoice



return 0;

}



For the Declaration of variables were used 2 rows to distinguish, visually, input and output variables.

It now adds a description of the program. This is not to explain what does the program extensively (reading from a computer screen is difficult and time-consuming) but non-redundant phrases that enter are as short as possible by eliminating words that do not increase the comprehensibility (for example delete articles), but also that they are as much as possible to clarify the issue:

#include <iostream>

using namespace std;



int main ()

{

int qven, pzun; q. sold, unit price single sale

int totf; total invoice



cout < < "invoice total Computation by row data" < < endl;



return 0;

}



the encoding of the algorithm predicts comment lines, which show the various stages of processing and explain what is processing, where the code explains how they should be treated to obtain that data processing.

#include <iostream>

using namespace std;



int main ()

{

int qven, pzun; q. sold, unit price single sale

int totf; total invoice



cout < < "invoice total Computation by row data" < < endl;



initializing invoice total



first invoice line



processing lines



While (qven > 0) {



calculate the row total



Update invoice total



other line



};



total output



return 0;

}



The first part of the program includes a sequence that includes the initialization of total amount (totalizer) and input the first element of looping (the first line of the invoice). Thereupon it is necessary to insert a loop to loop processing rows. At this point, as called for in the loop control condition, you need to decide on the termination of the processing. Because the problem is not specified the end of lines to consider you can take the acquisition of values that are valid, for example, the quantity of items sold: no sense in fact account for so much negative values or the value null. A speech like that could have been done considering the unit price. The sequence of operations to be performed ends with the output of the total invoice.


At this point can be detailed the stages: How do processing is established taking into account the encoding, each time, the code snippet below the single line of comment. Isolate themselves mentally the individual operations to be carried out:

first invoice line



"data line" cout < < < < endl

< < "quant. sold and unit price separated by space "< < endl

< < "(0 = < to finish)";

CIN >> qven >> pzun;



The complete code is listed below where you are adding even a temporary variable of work required to keep the total of the individual invoice line necessary for updating the invoice total:

#include <iostream>

using namespace std;



int main ()

{

int qven, pzun; q. sold, unit price single sale

int totf; total invoice

int totr; total row



cout < < "invoice total Computation by row data" < < endl;



initializing invoice total



totf = 0;



first invoice line



"data line" cout < < < < endl

< < "quant. sold and unit price separated by space "< < endl

< < "(0 = < to finish)";

CIN >> qven >> pzun;



processing lines



While (qven > 0) {



calculate the row total



totr = qven * pzun;



Update invoice total



totf + = totr;



other line



"data line" cout < < < < endl

< < "quant. sold and unit price separated by space "< < endl

< < "(0 = < to finish)";

CIN >> qven >> pzun;

};



total output



cout total invoice "< totf < < < < < endl;



return 0;

}



Perhaps the use of comments might seem like overkill but this only depends on triviality, from the point of view of the amount of code, the coded algorithm.

Reading only comment lines you will understand immediately what the program does and where. This is essential to identify the points of intervention for maintenance.


Vectors, strings and advanced constructs

Data types and type modifiers

A computer's processing involve data that can be of various types. The same processing can provide different results depending on the type of data: If you consider, for example, 2 and 12 and want to establish an order, the answer will be different depending on whether you mean the two data as numbers or as characters. In the first case, by referencing the value, the answer is 2, 12. If, instead, the sorting should be understood broadly, the answer will be 12, 2 (similarly to AB, B). It is necessary to determine in what sense intended values.

In General, in relation to the type of processing, in computer science a distinction is made between type character or alphanumeric and numeric types. If the data you want to perform arithmetic operations, these must be defined as numeric, otherwise be defined as type character.

Actually the situation is more complex: If for a char type there is very little to say, the numeric type is not indifferent for storage in computer memory. Suffice it to say that the numbers are infinite and that can also be the decimal part of a number, which the computer memory is limited, that the internal encoding is in binary and then extensive representations for even small numbers as the value, to state that there can be multiple alternatives because in-memory footprint and the precision with which you want to store the number.

In addition, to the above, that in real-world applications data, almost never, are simple but often occur in more complex structures.

Programming languages provide a set of elementary types and methods to construct complex structures: the user types that will be covered later.

C++ provides 6 elementary types identified by keywords: char, int, float, double, bool, void. Aside from the void that will be addressed below:

variables of type char may preserve, each, a character. The character can be stored in the variable using the usual way, input stream, cin, or, in an assignment statement, enclosing it between single quotes

...

char alpha, beta;

CIN >> alpha; receives a keyboard character and puts it in the variable

Beta = ' Z '; assign directly to the character

...



variables of type int, float, double can hold numbers. These types also allow the use of modifiers that vary the memory footprint of the variable and, therefore, the characteristics of the number stored. Allowed modifiers are short, long, unsigned.

#include <iostream>

#include <limits>

using namespace std;



int main ()

{



cout < <int> "bit integer" numeric_limits <: igits <:d < < < endl;

cout "whole numbers" numeric_limits < < <int> < igits10 <:d < <: endl;

cout < <int> "minimum" numeric_limits <: min () < < < < endl;

cout "max full" numeric_limits < < <int>:: max () < < < < endl;



cout "\nbit short" numeric_limits < < <short> <:d < igits < < endl:;

cout "digit short" numeric_limits < < <short> < igits10 <:d < <: endl;

cout < <short> "minimum short" numeric_limits <: min () < < < < endl;

"best short" cout < <short> < numeric_limits:: max () < < < < endl;



cout < <float> "\nbit float" numeric_limits <: igits <:d < < < endl;

cout < <float> "digits float" numeric_limits <: igits10 <:d < < < endl;

cout < <float> "minimum float" numeric_limits <: min () < < < < endl;

"best float" cout < < <float> numeric_limits:: max () < < < < endl;



cout < <double> "double \nbit" numeric_limits <: igits <:d < < < endl;

cout "double digits" numeric_limits < < <double> < igits10 <:d < <: endl;

cout < <double> "minimum double" numeric_limits <: min () < < < < endl;

cout "max double" numeric_limits < < <double>:: max () < < < < endl;



cout < < "long double \nbit" <:d < long double >: igits < numeric_limits < < endl;

"long double digits" cout < < < < igits10 <:d < long double >: numeric_limits < endl;

"minimum long double" cout < < < < numeric_limits < long double >:: min () < < endl;

maximum "long double" cout < < < < numeric_limits < long double >:: max () < < endl;



return 0;

}


The proposed example is to display some important features of the variables declared in that way. In particular prompted the view, for each quantity type, bit busy (digits), quantity digits of precision (digits10), minimum (min) and maximum (max) can be maintained. It is not important to explain the meaning of individual rows, it is important to know what produces this code because it is critical when writing any program, learn about the degree of reliability of a numeric value stored and how to declare the variable so that the correct storage.

The machine used for testing of programs reported in these notes, and the compiler used, you get these results:

bit integer 31

whole 9 digits

minimum integer-2,147,483,648

maximum integer 2,147,483,647



bit short 15

digits short 4

minimum short-32768

maximum short 32767



24-bit float

float 6 digits

minimum float 1.17549 e-38

maximum float 3.40282 and +38



bit double 53

double digits 15

minimum double 2.22507 e-308

maximum double 1.79769 and +308



long double 64 bits

long double digits 18

minimum long double 3.3621 e-4932

maximum long double 1.18973 and +4932



Each variable of type int is 31 bits in memory (actually 32 but a bit is reserved to the mark), it can contain only integers and permissible values vary between the margins reported (range of representation). If you apply the modifier short, the memory footprint change and thus the range of representativeness.

...

int a;

short b; It is not necessary to specify int

...

a = 15;

b = 20;

...



If you want to store a number with integer and decimal part you must declare the variable of type float or double floating (floating point). In these cases the problem, to consider, not the margin of representativeness, because both will preserve numbers with extremely high values (see the minimum and maximum value written in exponential notation), but accuracy. The float type uses 24 bits and guarantees six digits of precision (single precision). In practice the number can be quite large, as value (1038) but cannot contain more than 6 digits other than 0: Okay 12,340,000,000,000,000 but not 123,456,789. The second value is not stored properly.

The double type, at the cost of increased memory footprint, provides more precise figures (double precision). If you have need for even more precision you can declare a variable of type long double, and you get to 18 (quadruple precision).

...

float c;

double d;

long double e;

...

c = 123.23;

d = 456,970,345;

e = 789.0; in any case it should be inserted the decimal part!

...



The unsigned modifier might, for example, be no need to use it to increase the margin of representation of an int: instead of using 31 bits for the number and 1 bit for the sign, you would use all 32 bits to store the numeric value. The variable may contain numbers, up to twice the previous value, but only positives.

variables of type bool are used when you need to store result indicators/not allow registration of events and symbolic values true and false.

...

bool test;

test = false;

If (the < 100)

test = true;

...

Thanks for reading ;)

Previous article here: [Tutorial] How to start programming in C++ (Part 2)
 
L

LabZero

Guest
#3
Software Engineering: the writing style

A key point in writing a program is the coding style. Follow the rules for writing the program facilitates the understanding and care and also, ultimately, scripture itself. The software maintenance for the correction of errors encountered during use, for adding new features for editing functionality and maintenance costs may be higher development costs. A good writing style of the programs is an integral part of the documentation and programs need to be understood.
C++ is a widely used language and, as mentioned above, it is important the writing style in order to understand the code.
Analyzing a C++ malware, long ago, it was easy to see the malcoder hasn't provided the startup regkeys in HKLM, since they would require administrative permissions, so he inserted a .manifest with the request for execution: HKCU (Current User) without prompting from the user.
It was present a disabler within a secondary thread running from main () that controls the execution of some processes like taskmanager, regedit etc.. and block them, thus avoiding having to tweak the registry what else would only increase the antivirus detections.

However ... a well written mal-code.