C++ concepts

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

disjunction

If you are in the mall or I am in the mall, one of us will buy a gift for Mom. Appearance of the word "or" means that the purchase depends on at least one of these conditions. In the logic such a compound is called a disjunction.

function

Imagine a function as a black box, where you can insert something into it (it is not always necessary) and take something new out of it like out of a magic hat. Things used to be put in the box are called function arguments (or function parameters). Things used to be taken out of the box are called function results.

control variable

The variable used for counting the loop's turns. Notice, that the control variable doesn't have to be declared before it is used within the for loop. It could be declared inside the loop but in this case it will be available during and only during the loop execution. Here is the example: for(int i = 0; i < 100; i++) { /* the body goes here */ }

header files

These files contain a collection of such preliminary information about ready-made blocks which can be used by a program.

keywords or (more precisely) reserved keywords.

They are reserved because you mustn't use them as names: neither for your variables, nor functions or any other named entities you want to create. The meaning of the reserved word is predefined and mustn't be changed in any way. Ex. int, and, and_eq, asm, auto, bitand, bitor, bool, break...

return

Used in the function it causes the end of function execution. If you perform "return" somewhere inside a function, this function immediately interrupts its execution. return 0; //program finished correctly return 1; //something went wrong in the program

continue

behaves as the program suddenly reached, the control variable is modified (in the case of "for" loops) and the condition expression is tested.

breack the line

First, we can use one of the control characters named "newline" and coded as \n (note: we use two characters to write it down but the compiler gets it as one character - don't be misled). The newline character forces the console to complete the current line and to start a new one. Exactly the same effect may be achieved using a manipulator named endl (as "end line"). cout << "1\n2" << endl << "3\n"; output: 1 2 3

portability

If there is a translator designed for a specific computer, your program could be run without any problems. In other words, the programs written in high-level languages could be translated into any number of different machine languages and thus make them able to be used on many different computers.

conjunction

If we have some free time and the weather is good we will go for a walk. We have used the conjunction "and" which means that going for a walk depends on the simultaneous fulfillment of the two conditions.

manipulator

If you want a value of type int to be presented as a fixed-point hexadecimal number, you should use the so-called manipulator. A manipulator is a special kind of entity which is able to instruct the stream that the data form has to be changed immediately. All elements outputted after the manipulator activation will be presented in the desired form. The manipulator designed to switch the stream into the hexadecimal mode is named hex. The snippet presented on the bottom will output a string consisting of characters 'F' and 'F'. int byte = 255; cout << "Byte in hex: " << hex << byte; Technically, a manipulator is a function which changes one of the output stream's properties named basefield. The property is used to determine what number should be used as a base during the conversion of any int value into human readable text. Two important facts should be commented on here: any manipulator starts its work from the point it was placed on and continues its work even after the end of the cout statement; it finishes working only when another manipulator cancels its action; the name of the manipulator may be in conflict with any other name declared by the programmer; e.g. you can have your own variable named hex which could hide the manipulator's name; such conflicts are resolved by a specialized mechanism called namespace; we will discuss it later. int byte = 255; cout << hex << byte; cout << byte << dec << byte; Note: the dec manipulator switches the stream into a decimal form of representation. We don't have it explicitly in most of the cases since the decimal is a default working mode for output streams. The snippet will output the three specimens of the same value: 1.- FF as a hexadecimal representation of 225 (as an effect of the hex manipulator) 2.- FF again (the previous hex activation is still working here) 3.- 255 (as a result of the dec manipulator activation) The oct manipulator switches the stream into the octal mode.

cout

If you want to print a value of integer variable to the screen the only thing you have to do is to send it to the cout stream through the "<<" operator which clearly indicates the desired direction of data transfer. Both << operator and the cout stream are responsible for two important actions: -converting the internal (machine) representation of the integer -value into the form acceptable for humans -transferring the converted form to the output device e.g. console Ex. int herd_size = 110; cout << herd_size; int herd_size = 123; cout << "Sheep counted as far: " << herd_size; Cout is able to recognize the actual type of its element even when it is an effect of a conversion. char Char = 'X'; int Int = Char; cout<<Char<<" "<<(int)Char<<" "<<Int<<" "<<(char)Int; outputs the following text to the screen: X 88 88 X

post-increment and pre-increment operator

Operation: ++Variable --Variable Effect: Increment/decrement the variable by 1 and use its value already increased/reduced. Operation: Variable++ Variable-- Effect: Use the original (unchanged) variable's value and then increment/decrement the variable by 1. Such behavior justifies the presence of the prefix pre- (before) and post- (after) in the operators names. Pre- because the variable is modified first and then its value is used; post- because the variable's value is used and then the variable is modified. Variable++ post-increment operator ++Variable pre-increment operator Variable-- post-decrement operator --Variable pre-decrement operator they have the right-side binding

increment operator and decrement operator

SheepCounter = SheepCounter + 1; is the same as SheepCounter++; The "+ +" is called the increment operator. The "--" is called the decrement operator. We have presented to you the ++ and -- operators put after a variable (a specialist in the syntax of programming languages would say that they are used as postfix operators). However, both operators can be put in front of a variable (as prefix operators), like this: ++SheepCounter; --DaysUntilHoliday;

algorithm

Structured and semi-formal description of each step of the program

hexadecimal numbers.

Such number should be preceded by the prefix written as 0x or 0X. 0x123 is a hexadecimal number with the (decimal) value equal to 291.

instruction list (IL)

The IL is in fact an alphabet of a language, which is commonly known as a machine language. This is the simplest and the most primary language we can use to give commands to our computer. We can say, it's a computer's mother tongue.

escape character

The \ character (called backslash) acts as a so-called "escape character" because by using the \ we escaped from the normal meaning of the character that follows the slash. In this example, we escaped from the usual role of the apostrophe (i.e. delimiting the literals of type char). Character = '\''; You can also use the escape character to escape from the escape character. Character = '\\';

binding

The binding of the operator determines the order of computations performed by some operators with equal priority, put side by side in one expression. Most operators in the "C++" language has the left-sided binding, which means that the calculation of the presented expression is conducted from left to right i.e. 3 will be added to 2 and 5 will be added to the result. Ex. 2 + 3+ 5

cin

The cin stream along with the extraction operator are responsible for: -transferring the human-readable form of the data from the input device e.g. console -converting the data into the internal (machine) representation of the value being inputted Using an input stream we must explicitly specify the variable that is able to store the data entered by the user. In cout it may not be a variable. It may be an expression as well

linking

The compiling splits into two phases - a compilation of your source in order to translate it into machine language and joining (or gluing) your executable code with the executable code derived from other developers into a single and unified product. The program which conducts the process is named linker.

||

The disjunction is the operator is the digraph || (bar bar). It is a binary operator with its priority lower than && (just like "+" compared to "*").

literal

The literal is a symbol which uniquely identifies its value. Some prefer to use a different definition: the literal means itself. -Character: this is not a literal; it is probably a variable name; when you look at it, you cannot guess what value is currently assigned to that variable -'A': this is a literal; when you look at it you can immediately guess its value; you even know that it is a literal of the char type -100: it's a literal, too (of the type int) -100.0: it's another literal, this time of the float type -i + 100: it is a combination of a variable and a literal joined together with the + operator; such structure is called an expression

integers and floating-point numbers

The numbers handled by modern computers are of two types: -integers, that is, those which are devoid of the fractional part -floating-point ones (or simply floats) that contain (or are able to contain) the fractional part This distinction is very important and the boundary between these two types of numbers is very strict. Both of these kinds of numbers significantly differ in how they are stored in a computer memory and in the range of acceptable values.

fixed and scientific

The output streams try to output float values in a form which is more compact and the decision is taken for every printed float value. E.g. the following snippet float x = 2.5, y = 0.0000000025; cout << x << endl << y << endl; will produce the following output on the screen: 2.5 2.5e-009 The former presentation is referred to as "fixed point" while the latter as "scientific" (we introduced that term when we were discussing floating point literals). There are two manipulators designed especially to implicitly choose the desired presentation depending on the user's actual needs and preferences: Their names are: fixed scientific Note that initially the streams are set neither to the fixed nor to the scientific mode but to the default (automatic) mode. The use of any of the above manipulators switches the stream into the desired mode; however, the return to the default way of processing floats is not possible by the use of any of the manipulators. You have to use a special function for that purpose (we intentionally omit this issue here). Ex. float x = 2.5, y = 0.0000000025; cout << fixed << x << " " << y << endl; cout << scientific << x << " " << y << endl; output: 2.500000 0.000000 2.500000e+000 2.500000e-009

%

The remainder operator is a quite peculiar because it has no equivalent among traditional arithmetic operators. It is a binary operator and both arguments cannot be floats (don't forget that!). Look at the example. int i,j,k; i = 13; j = 5; k = i % j; You cannot compute the remainder with the right argument equal to zero. We hope you can guess why.

-

The subtraction operator is obviously the "-" (minus) sign, although you should note that this operator also has another meaning - it is able to change the sign of a number. int i,j; i = -100; j = -i; In such "subtracting" applications the minus operator expects two arguments: the left (a minuend in arithmetical terms) and right (a subtrahend). As you have probably guessed, the variable j will be assigned the value of 100. We used the minus operator as the unary operator, as it expects only one argument - the right one. The same dual nature is expressed by the "+" operator, which can be also used as a unary operator - its role is to preserve the sign.

declaration

The variable comes into existence as a result of a declaration. A declaration is a syntactic structure that binds a name provided by the programmer with a specific type offered by the "C++" language. Ex. int Counter; int variable1, account_balance, invoices;

Char values are int values

There is an assumption in the "C++" language that may seem surprising at the first glance: the char type is treated as a special kind of the int type. This means that: -You can always assign a char value to an int variable; -You can always assign an int value to a char variable but if the value exceeds 255 (the top-most character code in ASCII) you must expect a loss of value; -Value of the char type can be subject to the same operators as the data of type int char Char; Char = 'A'; Char += 32; Char -= ' ';

double

Variables of type double may differ from the variables of type float not only in range but also in accuracy. What does this mean? The data stored in the floating-point variable has finite precision - in other words, only a certain number of digits are precisely stored in the variable. For example, we expect that the value: 1111111111111111111.111111111111111111111 will be stored by a specific type of computer as: 1111111131851653120.000000 We say that the variable saves (only) 8 precise digits. This is within the expected accuracy of 32-bit long floats. Using a double (which is usually 64 bit long) guarantees that the variable will save more significant digits - about 15-17. This is where the name double came from - its accuracy is doubled comparing to float.

parentheses

We are always allowed to use parentheses which are able change the natural order of calculation. In accordance with the arithmetic rules, subexpressions in parentheses are always calculated first. You can use as many parentheses as you need and they are often used to improve the readability of expression, even if they don't change the order of operations.

preprocessor directive

What changes the preprocessor will introduce is fully controlled by its directives.

loss of accuracy

What happens when we are forced to convert integer values into float values or vice versa? The transformation from the type int into the float is always possible and feasible but can cause loss of accuracy. There is another aspect of the operation: converting a float into an int is not always feasible. Integer variables (like the floats) have a limited capacity. They cannot contain arbitrarily large (or arbitrarily small) numbers. Ex. int i; float f; f = 1E10; i = f; Certainly a loss of accuracy will occur but the value assigned to the variable i is not known in advance. In some systems it may be the maximum permissible int value, in others an error occurs, in others still the value assigned can be completely random. This is what we call an "implementation dependent issue". It's the second (and uglier) face of the "software portability".

do loop

acts like a mirror image of the while loop. We say so because in that loop: condition is checked at the end of body execution the loop's body is executed at least once even if the condition is not met This loop is called the "do" loop. Its simplified syntax is listed here do statement; while(condition); do { statement_1; statement_2; : : statement_n; } while(condition);

programming language

defined by a set of certain rigid rules, much more inflexible than any natural language.

\r

denotes the return to the beginning of the line and is sometimes called a CR (Carriage Return - "carriage" was the synonym of a "print head" in ancient times); printers respond to this character as if they were told to re-start printing from the left margin of the already printed line.

floating numbers.

designed to represent and to store the numbers that (as a mathematician would say) have a non-empty decimal fraction. Ex. 2.5 //never use ',' instead of '.' -you can omit zero 0.4 is the same as .4 the decimal point is essentially important in recognizing floating-point numbers in "C++" . 4 is an int. 4.0 is a float. We can say that the point makes a float. computers uses different methods for storing floats and ints in their memory.

lexicon

determine which symbols (letters, digits, punctuation marks, and so on) could be used in the language. Any program written by us must be correct in these three ways: lexically, syntactically and semantically. Otherwise, it will neither run nor produce acceptable results.

hard coding

encode all the needed data inside the source code

hierarchy of priorities

hat phenomenon that causes some operators to act before others is known as the hierarchy of priorities. The "C++" language precisely defines priorities of all operators and assumes that operators of larger (higher) priority perform their operations before the operators with lower priority.

De Morgan's laws

he negation of a conjunction is the disjunction of the negations. The negation of a disjunction is the conjunction of the negations. Let's try to write the same using the "C++" language → !(p && q) == !p || !q !(p || q) == !p && !q

type

the characteristic of a number which determines its kind, range and application. attribute that uniquely defines which values can be stored inside the variable.

\a

(as alarm) - is a relic of the past when the teletypes were often used to communicate with computers (are you sure that you know what the teletype is?); the sending of this character to a teletype turns on its ringer hence the character is officially called BEL (as bell); it is interesting that if you try to send such a character to the screen, you will hear a sound - it won't be a real ringing but rather a short beep.

== and !=

(equal equal) operator . It is a binary operator with a left-side binding. It needs two arguments and checks if they are equal. low priority. not equal? binary operator and has the same low priority.

scientific notation

300000000 is the same as 3E8 6.62607 · 10-34 (plank constant) is the same as 6.62607E-34 The letter E (you can also use the lower case letter e - it comes from the word exponent) is a concise record of the phrase "times ten to the power of". Note: the exponent (the value put after the "E") has to be an integer. the base (the value put in front of the "E") may be an integer.

assignment operator

= does not mean is equal to, but assign a value. Ex. x = x + 1; Take the current value of the variable x, add 1 to it and store the result in the variable x

namespace

A namespace is an abstract container or environment created to hold a logical grouping of unique entities (blocks). An entity defined in a namespace is associated only with that namespace. If you want to use many of the standard C++ entities (we are going to tell you about them later) you must insert the using namespace instruction at the top of each file, outside of any function.

setbase manipulator

Directly instructs the stream what base value it should use during a conversion. The only acceptable values for the setbase parameter are 8, 10 and 16. Note: it requires the header file iomanip to be included (the three former manipulators don't). #include <iostream> #include <iomanip> using namespace std; int main(void) { int byte = 255; cout << setbase(16) << byte; return 0; }

break

Exits the loop immediately and unconditionally ends the loop's operation; the program begins to execute the nearest instruction after the loop's body;

comments

Good and responsible developers describe each new created important entity; in particular, explaining its role of the parameters and the values modified or returned as a results and what the code actually does. How does one leave such a trace in the source code? It has to be done in a way that won't force the compiler to interpret it as part of the code. The remark inserted into the program which is omitted at the time of compiling, is called a comment. The "C++" language supports two ways of inserting comments: // line comments and /*block comments*/ it is not allowed to nest one block comment inside another block comment. ( like /* int i; /* int j; */ int k;*/)

octal number

If an integer number is preceded by the 0 digit, it will be treated as an octal value. It means that the number must contain digits taken from the 0..7 range only. 0123 is an octal number with the (decimal) value equal to 83

#

Its presence in that place means that the content of this line is the so-called preprocessor directive. The prefix "pre" suggests that these operations are performed before the full processing (compilation) takes place.

&&

Logical conjunction operator in the "C++" language is a digraph && (ampersand ampersand). It is a binary operator with a priority that is lower than the one expressed by the comparison operators. It allows us to code complex conditions without the use of parentheses like this one → Counter > 0 && Value == 100

\n

The "C++" language allows us to escape in some other circumstances. \n - denotes a transition to a new line and is sometimes called an LF (Line Feed) as printers react to this character pulling out the paper by one line of text

<<

The << operator itself is sometimes referred to as an insertion operator as in fact it inserts a string of characters into the character device (e.g. a console).

compilation

The process of the translation from a high-level language into a machine language. Made by a specialized computer program called compiler.

char

To store and manipulate characters, the "C++" language provides a special type of data. This type is called char, which is an abbreviation of the word "character".

bool

Variables of this type are able to store only two distinctive values: true and false. Note: all these new words (bool, true and false) are keywords. Don't forget that. Ex. bool developer_is_hungry = false; To be honest, the bool type is only a very special variant of the int type. It's very short (variables of this type occupy only 8 bits, which is still too much, because one bit would be enough). It behaves like an int inside expressions (true is equivalent to 1 while false results in the value of 0).

#include

When the preprocessor meets that directive, it replaces the directive with the content of the file whose name is listed in the directive

operator

a symbol of the programming language, which is able to operate on the values. We begin with the operators, which are associated with widely recognizable arithmetic operations Ex. + - / * %

syntactic candies

break; continue' Let's say for the sake of accuracy that their existence in the language is not necessary - an experienced programmer is able to code any algorithm without such instructions. It was proved by the famous Dutch computer scientist Edsger Dijkstra in 1965. Such additions which don't improve the language's expression power but only simplify the developer's work are sometimes called the syntactic candies.

unsigned

can be used with int type and char, but not float. If we came to the conclusion that a variable will never be a negative value, we can use the unsigned modifier → Ex. unsigned int Positive; Of course we can omit the int as usual: unsigned Positive;

<< or >>

digraph which specifies the direction in which the text is send

compound statement or Block

everything that is between braces { } The block is treated as a single instruction by the compiler .

>>

extraction operator.

false and true

false is 0 true is 1 (or any other value different from 0)

division by zero

float x,y; x = 0.0; y = 1.0 / x; In the following example the compiler won't tell you a thing but when you try to execute that code the result of such an operation may be surprising. It's a special featured value named inf (as in infinitive). Generally, that kind of illegal operation is a case of so-called exception. You can discover exceptions in your program and react to them accordingly.

for loop

for(initialization; checking; modifying) { /* the body goes here */ } it is more important to count the "turns" of the loop than to check the conditions. //equivalent to: int i; i = 0; while (i < 100) { /* the body goes here */ i++; } initialization; while (checking) { /* the body goes here */ modifying; } The for loop has an interesting singularity. If we omit any of its three components it is presumed that there is the number 1 instead. One of the consequences of that fact is that the loop written in the following way is an infinite loop (can you explain why?) for( ; ; ) { /* the body goes here */ }

bitwise operators

four operators that allow you to manipulate singe bits of data.

sqrtf(float);

function sqrtf (square root float) and requires exactly one argument. included in cmath header file.

conditional if

if(true_or_false) do_this_if_true;

hex oct dec manipulators

int byte = 255; cout << hex << byte; cout << dec << byte; cout << oct << byte;

prototype

it is like a label affixed to a function and announcing how you can use that function in your program. The prototype says nothing about what the function is intended to. But it says... -what is the result of the function? -what is the name of the function? -how many parameters does the function have and what are their names? ex. int main(void)

else

keyword (reserved word). The statement which begins with "else" tells us what to do if the condition specified for the if is not met. if (true_or_false_condition) perform_if_condition_true; else perform_if_condition_false; if(TheWeatherIsGood) { GoForAWalk(); HaveFun(); } else { GoToATheatre(); EnjoyTheMovie(); } HaveLunch();

std namespace

ll elements of the standard C++ library are declared inside the namespace called std. ex. using namespace std;

modifiers

long - is used to declare that we need a wider range of ints than the standard one; short - is used to determine that we need a narrower range of ints than the standard one; unsigned - is used to specify that a variable is used only for non-negative numbers; although it may be surprising, we can use that modifier together with the type char; we will explain it soon. We can also mix some of the modifiers together - take a look → unsigned long int HugeNumber; We can remove the word int and the declaration will preserve its meaning: unsigned long HugeNumber; Ex. unsigned short int Lambs; // same as unsigned short Lambs;

long

long - is used to declare that we need a wider range of ints than the standard one; can be used just with int type, not float, not char. Ex. long int Ants; The Ants variable will occupy more (or just as many) bits than the standard int (e.g. 64 bits so it can be used to store numbers from the range of [-9223372036854775808 .. 9223372036854775807] Note - we can omit the word int again: long Ants; It is also necessary to add an important remark. So far we used integer literals, assuming that all of them are of type int. It's generally true but there are some cases when the compiler recognizes literals of a type long. This will happen if: a literal value goes beyond the acceptable range of type int; a letter L or l is appended to the literal, such as 0L or 1981l - both of these literals are of type long

cmath

mathematics header file

conditional instruction(or conditional statement).

mechanism which will allow us to do something if a condition is met and not to do it otherwise.

pseudocode

notation which is not a programming language at all (it could be neither compiled nor executed) but is formalized, concise and readable.

\0

nul. Is a character that does not represent any character;

logical operators

operators to build conjunctions and disjunctions.

high-level programming languages

ridge between the people's language (natural language) and a computer language (machine language). That bridge is also a language - an intermediate common language for both humans and computers working together. There is no need to learn many different machine languages - it's enough to know one high-level programming language. If there is a translator designed for a specific computer, your program could be run without any problems.

short

short - is used to determine that we need a narrower range of ints than the standard one; can be used just with int type, not float, not char. The Counter variable will use fewer (or just as many) bits than the standard int (e.g., it could be 16 bit long - in this case, the range of the variable will be suppressed to the range of [-32768 to 32767]). Ex. Short int Counter; The word int may be omitted as all the declarations lacking a type name are considered as specifying int by default, like this: short Counter;

cout

show a text on the screen ex. cout << "hola";

variables

special "containers" , the content of a container can be varied in (almost) any way. What does every variable have? -a name -a type -a value If you want to give a name to the variable you must follow some strict rules: -the name of the variable must be composed of upper-case or lower-case Latin letters, digits and the character _ (underscore); -the name of the variable must begin with a letter the underline character is a letter (strange but true) -upper- and lower-case letters are treated as different (a little differently than in the real world - Alice and ALICE are the same -given names but they are two different variable names, consequently, two different variables)

basefield

stream's property named basefield. The property is used to determine what number should be used as a base during the conversion of any int value into human readable text.

syntax

the appropriate ways of collating the symbols

semantics

the meaning of every statement expressed in the given language

initiator

the part of the declaration placed on the right side of the = sign is called an initiator. The initiator which you saw before was a literal but you can use more complex expressions like these ones float PI = 3.1425;

numerical anomalies

the phenomenon of loosing precision when dealing with floats.

language

tool for expressing and recording human thoughts, to understand and to be understood.

function body

what the function is intended to, it is written inside the function .

while loop

while(conditional_expression) statement; If you notice some similarities to the if instruction it is quite reasonable. Indeed the syntactic difference is only one: we put the word "while" instead of the "if". The semantic difference is more important: when the condition is met, if performs its statements exactly once; while repeats the execution as long as the condition evaluates to "true". int main(void) { int counter = 5; while(counter--) cout << "I am an awesome program" << endl; return 0; }


Kaugnay na mga set ng pag-aaral

Romanian orphan studies: Effects of institutionalisation

View Set

Biology, Chapter 1-4 Exam Review

View Set

NCLEX 10000 ENDOCRINE AND METABOLIC

View Set

Chapter 9 - Book and Quiz Questions

View Set

Fin 453 Chapter 17: The Central Bank Balance Sheet and Money Supply

View Set

ST for the ST - Chapter 1- Organizations and their acronyms

View Set

3. Mucho gusto. Encantado vs. Encantada (Pleased to meet you)

View Set