CPA Cap. 1
CPA Cap. 1
CPA Cap. 1
1/38
Programming Essentials in C++
run, or it will produce unacceptable results. You can be sure that you’ll encounter all of these errors, as
to err is human and it’s these fallible humans who write the computer programs.
The expressive power of programming languages is much, much weaker than natural languages.
We can’t (although we can try to) use such a language to express human emotions, and it’s hard to
imagine a declaration of love encoded inside a programming language. This is because the message
embedded inside a computer program is not intended for a human, but for a machine.
You might be asking yourself why we need to use a programming language at all, and that's a good
question. Let’s try to answer it.
2/38
Programming Essentials in C++
machine language. Moreover, the translation can be done by a computer, making the whole process fast
and efficient.
How great is that? You don’t need to learn a whole bunch of different machine languages – you
just need to know one high-level programming language. If there is a translator designed for a specific
computer, you can run your program without any problems. In other words, the programs written in
high-level languages can be translated into any number of different machine languages, and thus enable
them to be used on many different computers. This is called portability.
What is the most common use of C++? It is the so-called object programming language, i.e.
suitable mostly for large, complex applications, especially those working in graphic environments.
Knowing the C++ language is very helpful if you want to learn C# or Java. The conceptual apparatus
used by the C++ language is common for all object programming languages, as C++ is one of the
oldest languages of that class.
Compiler
to start
to write the text on the screen
to stop
This type of structured and semi-formal description of each step of the program is called an
algorithm. Sources of the word algorithm can be traced back to the Arabic language and originated in
early medieval times, and for us, this represents the beginning of computer programming.
Now, it's time to see our program. Here it is →
It looks a bit mysterious, doesn't it? Let’s check out each line of the program carefully, and
uncover its meaning and purpose. The description is not particularly accurate and those of you who
know a little C++ already will probably conclude that it’s too simplistic and somewhat childish. We did
this on purpose – we’re not building Rome in a day. Not even in a week!
Let's move on.
source_01_02_01_itsme.cpp
#include <iostream>
using namespace std;
int main(void) {
cout << "It's me, your first program.";
return 0;
}
#include <iostream>
5/38
Programming Essentials in C++
#include <iostream>
using namespace std;
int main(void) {
cout << "It's me, your first program.";
return 0;
}
6/38
Programming Essentials in C++
function is intended to do. It’s written inside the function and the interior of the function is called the
function body. The function body begins with the first opening bracket { and ends with the
corresponding closing bracket }. It might sound surprising, but the function body can be empty, which
means that the function does exactly nothing.
We can even create a function that is lazy – it can be encoded like this:
void lazy(void) { }
This drone provides no result (the first void), its name is “lazy”, it doesn't take any parameters
(the second void) and it does absolutely nothing (the blank space between brackets).
By the way, the names of the functions are subject to some fairly rigid constraints. More on this
later.
#include <iostream>
using namespace std;
int main(void) {
cout << "It's me, your first program.";
return 0;
}
In the C++ language it isn’t necessary to write just one statement per line. You can place two (or
more) statements on the same line, or split one statement into several lines, but bear in mind that
readability (for humans) is a very important factor. However, compilers, unlike humans, will never
complain about your style.
8/38
Programming Essentials in C++
For now, let's leave the floating-point numbers aside (that’s right: more on them later) and let’s
consider a question that’s maybe a bit banal at first glance: how does the C++ language recognize the
integers?
Well, it’s almost the same as when you write them on a piece of paper – they’re simply a string
of digits that make up a number. But there’s a catch – you can’t include any characters that are not
digits inside the number.
Take for example the number eleven million one hundred and eleven thousand one hundred and
eleven. If you took a pencil in your hand right now, you would probably write the number like this:
11,111,111
or (if you’re a Pole or a German) like this:
11.111.111
or even like this:
11 111 111
For sure, this makes it easier to read if the number consists of many digits. However, C++doesn’t
like this at all. You have to write this number as follows:
11111111
If you don’t, the compiler will shout at you. And how do you code negative numbers in C++? As
usual, by adding a minus. You can write:
-11111111
Positive numbers don’t need to be preceded by the plus sign, but you can do it if you want. The
following lines describe the same number:
+123
123
For now we’ll deal only with integers – we’ll introduce floating-point numbers very soon.
There are two additional conventions, unknown to the world of mathematics. The first of them
allows us to use the numbers in an octal representation. If an integer number is preceded by the 0 digit,
it will be treated as an octal value. This means that the number must contain digits taken from the 0 to 7
range only.
0123
is an octal number with the (decimal) value equal to 83.
The second allows us to use 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.
9/38
Programming Essentials in C++
Let's start with the issues connected with a variable’s name. Variables don’t magically appear in
our program. We (as developers) decide how many, and which variables, we want to have in our
program. We also give them their names, almost becoming their godparents. If you want to give a
name to the variable, you have to follow some strict rules:
the name of the variable can 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, and consequently,
two different variables).
These same restrictions apply to all entity names used in C++.
The standard of the C++ language does not impose restrictions on the length of variable names,
but a specific compiler may have a different opinion on this matter. Don't worry; usually the limitation
is so high that it’s unlikely you would actually want to use such long variable names (or functions).
Here are some correct, but not always convenient, variable names:
i
t10
Exchange_Rate
counter
DaysToTheEndOfTheWorld
TheNameOfAVariableWhichIsSoLongThatYouWillNotBeAbleToWriteItWithoutMistakes
_
The last name may be ridiculous from your perspective, but your compiler thinks it’s just great.
And now let's have a look at some examples of incorrect names:
10t (does not begin with a letter)
Adiós_Señora (contains illegal characters)
Exchange Rate (contains a space)
Let’s try to declare a variable of type int named Counter. The relevant portion of the program will
look like this:
int Counter;
What is declared by the following fragment of a program?
int Counter;
Counter = 1;
x=x+1
1.3.8 Keywords
11/38
Programming Essentials in C++
Take a look at the right side of the screen – you’ll see a list of words that play a very special role
in every C++ language program. They are called keywords or (more precisely) reserved keywords.
They are reserved because you can’t use them as names: neither for your variables, nor for your
functions or any other named entities you want to create. The meaning of the reserved word is
predefined and can’t be changed in any way.
Fortunately, because the C++ compiler is case-sensitive, you can modify any of these words by
changing the case of any letter, thus creating a new word, which is not reserved any more.
For example – you can't do this:
int int;
You can’t have a variable named int – it’s prohibited.
But you can do this instead:
int Int;
The compiler will be happy, very happy.
12/38
Programming Essentials in C++
/*************************************************
Counting sheep version 1.0 Author: Ronald Sleepyhead, 2012 email: rs@insomnia.org Changes: 2012-
09-13: Ginny Drowsy: counting black sheep improved
*************************************************/
like “two and a half” or “zero point four” we think of numbers which the computer considers to be
floating numbers.
2.5
.4
4.
The letter E (you can also use the lower case letter e - it comes from the word exponent) is a
concise representation of the phrase times ten to the power of.
Note:
the exponent (the value after the “E”) must be an integer.
the base (the value in front of the “E”) may or may not be an integer.
SPEED OF LIGHT
300000000 M/S
int i;
float x;
i = 10 / 4;
x = 10.0 / 4.0;
15/38
Programming Essentials in C++
int i;
float f;
i = 100;
f = i;
int i;
float f;
f = 100.25;
i = f;
int i;
float f;
f = 1E10;
i = f;
1.4.12 Operators
An operator is a symbol of the programming language, which is able to operate on the values. For
example, an assignment operator is the = sign. We already know that it can assign values to variables.
Now let’s look at some other operators available in the C++ language and find out which rules
govern their use and how to interpret the operations they perform. Let’s begin with the operators
associated with widely recognizable arithmetic operations. The order of their appearance is not
accidental. We’ll talk more about this afterward.
16/38
Programming Essentials in C++
+ - / * %
1.4.13 Multiplication
An asterisk * is a multiplication operator. If you take a look at the code here, you’ll see that the
variable k will be set to the value of 120, while the z variable will be set to 0.625.
int i,j,k;
float x,y,z;
i = 10;
j = 12;
k = i * j;
x = 1.25;
y = 0.5;
z = x * y;
1.4.14 Division
A slash / is a divisional operator. The value in front of the slash is a dividend, while the value
behind the slash is a divisor.
Look at the snippet of the program; of course, k will be set to 2, z to 0.5.
int i,j,k;
float x,y,z;
i = 10; j = 5;
k = i / j;
x = 1.0;
y = 2.0;
z = x / y;
float x;
x = 1.0 / 0.0;
float x,y;
x = 0.0;
y = 1.0 / x;
17/38
Programming Essentials in C++
1.4.17 Addition
The addition operator is the + (plus) sign, which most of us already know from maths class.
Again, take a look at the snippet of the program – as you can surmise, k is equal to 102 and z to
1.02.
int i,j,k;
float x,y,z;
i = 100;
j = 2;
k = i + j;
x = 1.0;
y = 0.02;
z = x + y;
1.4.18 Subtraction
The subtraction operator is obviously the – (minus) sign, although you should note that this
operator also has another meaning – it can change the sign of a number.
This is a good time to show you a very important distinction between unary and binary
operators (in the C++ language there is also a ternary operator – more on that a bit later).
As usual, let’s get acquainted with a snippet of the program – you can guess that k will be equal
to -100, while z will be equal to 0.0.
int i,j,k;
float x,y,z;
i = 100;
j = 200;
k = i - j;
x = 1.0;
y = 1.0;
z = x - y;
int i,j;
i = -100;
j = -i;
18/38
Programming Essentials in C++
Although such a construction is syntactically correct, using it doesn’t make much sense and it
would be hard to find a good rationale for doing it.
int i,j;
i = 100;
j = +i;
1.4.21 Remainder
The remainder operator is quite peculiar, because it has no equivalent among traditional
arithmetic operators.
Its graphical representation in the C++ language is the % (percent) character, which may look a
bit confusing. It’s a binary operator (it performs the modulo operation) and both arguments cannot be
floats (don't forget that!).
Look at the example →
The k variable is 3 (because 2 * 5 + 3 = 13).
Oh, and one more thing you need to remember: you cannot compute the remainder with the
right argument equal to zero. Can you guess why?
You probably remember what we said earlier about dividing by zero. And because division by 0
invokes undefined behaviour, the modulo operation, which relies on division, is undefined, too.
Well, that’s what the C++ Standard says. We have to accept that.
int i,j,k;
i = 13;
j = 5;
k = i % j;
1.4.22 Priorities
So far, we’ve treated each operator as if it had no connection with the others. Of course, in real
programming, nothing is ever as simple as that. Also, we very often find more than one operator in an
expression and then things can get very complicated very quickly. Consider the following expression.
If your memory hasn't failed you, you should remember from school that multiplications precede
additions. You probably remember that you have to multiply 3 by 5, keep the 15 in your memory, add it
to 2, thus getting the result of 17.
The phenomenon that causes some operators to act before others is known as the hierarchy of
priorities. The C++ language precisely defines the priorities of all operators and assumes that
operators of larger (higher) priority perform their operations before the operators with lower
priority.
So if we know that * has a higher priority than +, we can figure out how the final result will be
computed.
2+3*5
1.4.23 Bindings
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 have the
left-sided binding, which means that the calculation of this sample expression is conducted from left
to right, i.e. 3 will be added to 2, and 5 will be added to the result.
19/38
Programming Essentials in C++
Now at this point you might be snorting and saying that all children know perfectly well that
addition is commutative and it doesn’t matter in which order the additions are performed. And yes,
you're right, but not quite. Additions performed by the computer are not always commutative. Really.
We’ll show you this in more detail later. But for now, be patient and trust us.
2+3+5
2*3%5
int i,j,k,l;
i = 100;
j = 25;
k = 13;
l = (5 * ((j % k) + i) / (2 * k)) / 2;
10
20/38
Programming Essentials in C++
21/38
Programming Essentials in C++
They may seem a little strange at first, but they’ll grow on you. Let's discuss the effects of these
operators.
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.
The behavior of these operators justifies the presence of the prefix pre- (before) and post- (after)
in their names: pre- because the variable is modified first and then its value is used; and post- because
the variable’s value is used and then the variable is modified.
int i,j;
i=1;
j=i++;
int i,j;
i=1;
j=++i;
int i,j;
i = 4;
j = 2 * i++;
i = 2 * --j;
22/38
Programming Essentials in C++
i=i+2;
i*=2;
SheepCounter += 10;
23/38
Programming Essentials in C++
Now, however, we’ll ignore the string consisting of multiple characters and we’ll focus our
attention on single characters. We’ll come back to the problem of processing strings when we start
working on arrays, because in the C++ language all strings are treated as arrays.
char Character;
Character Dec Hex Character Dec HexCharacter Dec HexCharacter Dec Hex
(NUL) 0 0 (space) 32 20 @ 64 40 ` 96 60
(SOH) 1 1 ! 33 21 A 65 41 a 97 61
24/38
Programming Essentials in C++
(STX) 2 2 " 34 22 B 66 42 b 98 62
(ETX) 3 3 # 35 23 C 67 43 c 99 63
(EOT) 4 4 $ 36 24 D 68 44 d 100 64
(ENQ) 5 5 % 37 25 E 69 45 e 101 65
(ACK) 6 6 & 38 26 F 70 46 f 102 66
(BEL) 7 7 ' 39 27 G 71 47 g 103 67
(BS) 8 8 ( 40 28 H 72 48 h 104 68
(HT) 9 9 ) 41 29 I 73 49 i 105 69
(LF) 10 0A * 42 2A J 74 4A j 106 6A
(VT) 11 0B + 43 2B K 75 4B k 107 6B
(FF) 12 0C , 44 2C L 76 4C l 108 6C
(CR) 13 0D - 45 2D M 77 4D m 109 6D
(SO) 14 0E . 46 2E N 78 4E n 110 6E
(SI) 15 0F / 47 2F O 79 4F o 111 6F
(DLE) 16 10 0 48 30 P 80 50 p 112 70
(DC1) 17 11 1 49 31 Q 81 51 q 113 71
(DC2) 18 12 2 50 32 R 82 52 r 114 72
(DC3) 19 13 3 51 33 S 83 53 s 115 73
(DC4) 20 14 4 52 34 T 84 54 t 116 74
(NAK) 21 15 5 53 35 U 85 55 u 117 75
(SYN) 22 16 6 54 36 V 86 56 v 118 76
(ETB) 23 17 7 55 37 W 87 57 w 119 77
(CAN) 24 18 8 56 38 X 88 58 x 120 78
(EM) 25 19 9 57 39 Y 89 59 y 121 79
(SUB) 26 1A : 58 3A Z 90 5A z 122 7A
(ESC) 27 1B ; 59 3B [ 91 5B { 123 7B
(FS) 28 1C < 60 3C \ 92 5C | 124 7C
(GS) 29 1D = 61 3D ] 93 5D } 125 7D
(RS) 30 1E > 62 3E ^ 94 5E ~ 126 7E
(US) 31 1F ? 63 3F _ 95 5F 127 7F
Character = 'A';
If you want to use single character on the right side you can’t omit apostrophes under any
circumstances. If you try, the compiler might not like it.
Now let’s assign an asterisk to our variable. Like this →
Character = '*';
Character = '\'';
1.5.7 Literals
Okay, we think you’re ready for a new term: a literal. The literal is a symbol that uniquely
identifies its value. Some people prefer to use a different definition: the literal means itself.
Choose the definition that you think is clearer and look at the following simple examples:
Character: this is not a literal; it’s 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 immediately know its value; you even know that it is a
literal of the char type
100: it's a literal, too (of type int)
100.0: it's another literal, this time of the float type
i + 100: this is a combination of a variable and a literal joined together with the + operator; such a
structure is called an expression.
Character = '\\';
26/38
Programming Essentials in C++
Character = '*';
Character = '*\\;
\n
\r
\a
\0
27/38
Programming Essentials in C++
47 octal is 39 decimal. Look at the ASCII code table and you'll find that it’s the ASCII code for
an apostrophe, so this is equivalent to
'\''
(but only for computers implementing the ASCII code).
Character = '\47';
Character = '\x27';
char Char;
Char = 'A';
Char += 32;
Char -= ' ';
28/38
Programming Essentials in C++
==
1.6.3 Is x equal to y?
The question is trivial. Of course 2 is equal to 2. The computer will answer “true”.
2 == 2
1 == 2
i == 0
Here we have another developer who counts black and white sheep separately and can only fall
asleep when there are exactly twice as many black sheep as white ones.
The question is as follows →
Due to the low priority of the == operator, this question is treated as equivalent to this one:
BlackSheepCounter == (2 * WhiteSheepCounter)
BlackSheepCounter == 2 * WhiteSheepCounter
1.6.7 Question: is x not equal to y?
To ask this question, we use the != (exclamation equal). It’s a very close relative of the ==
operator. It’s also a binary operator and has the same low priority. Imagine we want to ask whether the
number of days left to the end of the world is currently not equal to zero →
If the answer is “true”, that gives us the chance to go to the theater or to visit our friends. If the
answer is “false”…well, that’s bad.
DaysUntilTheEndOfTheWorld != 0
30/38
Programming Essentials in C++
If the answer is “true” because Value1 is greater than or equal to Value2, the computer will assign
1 to Answer (1 is arguably different from zero). If Value1 is less than Value2, the variable Answer will
be 0.
++ -- + - unary
* / %
+ - binary
< <= > >=
== !=
= += -= *= /= %=
if(true_or_not) do_this_if_true
31/38
Programming Essentials in C++
if(TheWeatherlsGood) GoForAWalk();
HaveLunch();
32/38
Programming Essentials in C++
int herd_size = 123; cout << "Sheep counted so far: " << herd_size;
33/38
Programming Essentials in C++
int square_side = 12; cout << "The square perimeter is: " << square_side;
int byte = 255; cout << "Byte in hex: " << hex << byte;
34/38
Programming Essentials in C++
#include <iostream> #include <iomanip> using namespace std; int main(void) { int byte = 255; cout <<
setbase(16) << byte; return 0; }
char Char = 'X'; int Int = Char; cout<<Char<<" "<<(int)Char<<" "<<Int<<" "<<(char)Int;
35/38
Programming Essentials in C++
The snippet on the right → illustrates both methods and causes the console to display the
following three lines of text:
36/38
Programming Essentials in C++
transferring the human-readable form of the data from the input device e.g. a console
converting the data into the internal (machine) representation of the value being input.
37/38
Programming Essentials in C++
attempt to bend the rules of mathematics. Whether we see the result or not will be decided by the
conditional statement.
Now it’s time to focus on the use of floating point data and the sqrtf function.
Here’s the complete program →
source_01_07_15_squareroots.cpp
#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{ float value,squareroot;
cout << "Give me a number and I will find its square root:" << endl; cin >> value;
if(value >= 0.0)
{
squareroot = sqrtf(value);
cout << "You have given: " << value << endl;
cout << "The square root is: " << squareroot << endl;
}
return 0;
}
38/38