Download as pdf or txt
Download as pdf or txt
You are on page 1of 66

1

Lesson 1

Introduction
to Programming

Contents
1. Prolegomena ................................................................. 4
Opening Remarks..................................................................4
Historical Facts.......................................................................5
2. First View of Algorithms............................................... 9
The Concept of an Algorithm..............................................9
Algorithm Properties...........................................................10
Types of Algorithms: Linear, Branched, Cyclic................11
3. Graphical Description of an Algorithm...................... 14
The Concept of a Flowchart................................................14
Basic Symbols in Flowcharts..............................................14
4. Installing Microsoft Visual Studio 2019..................... 19
5. The First Project.......................................................... 27
Scenario 1. Commands are written
in an interpreted language..................................................28
Scenario 2. Commands are written
in a compiled language........................................................29

2
Сontents

The First Attempt.................................................................30


Example of Your First Program in C++............................34
Opening a Saved Project.....................................................37
6. Data Output................................................................. 39
P. S..........................................................................................43
7. Data Types................................................................... 45
Numeric Types.....................................................................46
Character Type.....................................................................47
Logical Type..........................................................................47
8. Variables and Constants.............................................. 49
Naming Rules.......................................................................50
Declaring and Using Variables and Constants.................50
Printing the Value of a Variable.........................................51
Application Examples..........................................................52
9. Data Input.................................................................... 58
10. Literals....................................................................... 63
11. Homework................................................................. 64

Lesson materials are attached to this PDF file. In order to get access
to the materials, open the lesson in Adobe Acrobat Reader.

3
Lesson 1

1. Prolegomena
Opening Remarks
Welcome to the world of programming! What is pro-
gramming? Perhaps, each of you has heard this word. To
paraphrase a famous quote, we can say: “Programmer, that
sounds proud!” And so it is. If you came across job-offer-
ing websites when surfing the Internet, you probably paid
attention to the payment that was offered to programmers.
And you might have wondered, why do programmers have
higher salaries? All according to the laws of the market:
there is a demand for programmers, but the number of
good specialists is too small at the moment. Of course, if
one could become a programmer in a short period of time
just by having memorized a number of terms, the profes-
sion would not be so popular. But do not worry! We, your
teachers, will try to do everything we can in order to not only
tell you how to code, but also teach you how to incorporate
programming in your life. However, our efforts should be
mutual. A teacher, no matter how hard he tries, will not be
able to teach the student, if the latter does not want it. Only
constant self-cultivation will help you master every aspect
of programming.
We sincerely hope that you will be fond of the magical
world of programming!
Before proceeding to the study of any science, it is always
necessary to find out how this science appeared, how it has
developed, what its roots and value in history are.

4
1. Prolegomena

Historical Facts
A 19th-century English mathematician Shanks spent more
than 20 years of his life to calculate π that was accurate to
707 significant digits after the point. This result got the glory
of the calculation record in the 19th century. However, later
it was discovered that Shanks made a mistake in the 520th
digit, and therefore all subsequent significant digits were
calculated incorrectly.
In 1804, a French inventor Joseph Marie Jacquard created
a “programmable” weaver’s loom. Punched cards interconnected
in the shape of a tape were used to control the loom. Guided
by the holes in the punched cards arranged in a different order,
wooden studs of the machine “reading device” determined
which threads were to lift, and which threads were to lower
in order to obtain the desired pattern. In 1890, a US inventor
Herman Hollerith developed an electromechanical tabulating
machine for punched cards. It was used for the tabulation
of results of the US population census. A tabulator compa-
ny founded by Hollerith later turned into the corporation
International Business Machines (IBM).
In 1936, a 25-year-old student from Cambridge University,
an Englishman Alan Turing, published a paper “On computable
numbers” which considered a hypothetical device (“Turing
machine”), suitable for solving any solvable mathematical or
logical problem — a prototype of a programmable computer.
In 1941, a German engineer Konrad Zuse built an op-
erational computer Z3, which was using a binary system.
Programs were recorded on a punched tape.
In 1945, a physicist John Mauchly and an engineer Prosper
Eckert from the  Higher Technical School, University of

5
Lesson 1

Pennsylvania (USA), built a fully electronic machine named


ENIAC. To program a machine, it was necessary to manually
install thousands of switches and plug hundreds of sockets in
the contact panel plugs. June 1, 1945, a Hungarian-born American
mathematician John von Neumann circulated a report called
“The First Draft of a Report on the EDVAC” which con-
tained the concept of storing computer instructions in its own
internal memory.
June 21, 1948, the first in the world memory-stored program
focused on the search of the largest factor of the current digit
was performed on the machine named Mark I at the University
of Manchester (UK).
In 1949, the computer EDSAC was designed under the lead-
ership of Maurice Wilkes. The designers who worked on EDSAC
introduced a system of mnemonic notations, where each machine
instruction was represented by a capital letter and automated
subroutine setup to a specific location in the memory. Maurice
Wilkes called the mnemonic scheme and subroutine library
an assembly system, hence the word “assembler.”
In 1949 in Philadelphia (USA), “Short Code” — the first
primitive programming language interpreter — was created
under the direction of John Mauchly.
In 1951 an American programmer Grace Hopper devel-
oped the first translator when she worked in Remington Rand.
Hopper called it a compiler.
In 1957, on the 20th floor of the IBM headquarters on
Madison Avenue in New York, the Fortran language (FORmula
TRANslation) was born. A 30-year-old mathematician John
Backus led the team of developers. Fortran is the first “real”
high-level language.

6
1. Prolegomena

In 1963, the programming language BASIC was created.


The founders of the language were John Kemeny and Thomas
Kurt, researchers at Dartmouth College. Under the direction
of the founders, the language was implemented by a group of
college students. The first dialect is known as Dartmouth BASIC.
1958–1968 were the years of development and improvement
of the programming language called Algol, whose name came
from the word-combination algorithmic language. Unlike
Fortran, mainly used in the USA and Canada, Algol was widely
distributed in Europe and the USSR. The language was created
by an international committee, which included European and
US scientists — John Backus, Peter Naur, Niklaus Wirth.
In 1970, Niklaus Wirth created a programming language
and named it in honor of a French physicist and mathemati-
cian Blaise Pascal. Wirth planned to use Pascal as a language
for teaching procedural programming. In 1972, a 31-year-old
system programming specialist from Bell Labs, Dennis Ritchie
developed the C programming language.
The first description of the language was given in the book
written by B. Kernighan and D. Ritchie. This description was
the standard for quite a long time, but some aspects were un-
clear and entailed many interpretations of C. To change that
situation, the Standardization Committee for C was formed
at the American National Standards Institute (ANSI).
In 1983, the standard of the language C known as ANSI
C was approved.
In the early 1980s, at the same Bell Laboratory, Bjarne
Stroustrup created, in fact, a new language as a result of ad-
ditions and extensions of C and named it “C with Classes.” In
1983, the name was changed to C++ (see plus plus).

7
Lesson 1

May 23, 1995, the company Sun Microsystems released


a new programming language called Oak. The language was
designed for programming consumer electronics. Later Oak
was renamed to Java and had been widely used in the devel-
opment of applications and server software.
In 2000–2001, a new programming language C# (see sharp)
specifically designed for the .NET platform was adopted and
standardized. The employees of the Microsoft Research (a
scientific research institute attached to Microsoft) — Anders
Hejlsberg, Scott Viltamut, Peter Golde and other well-known
experts, including Eric Meyer — were involved in the creation
of the language. The language version C# 2.0 was introduced
in spring 2005. It should be noted that one of the languages,
on which basis C# was created, was the good old C++.
After this little trip to the past, we can move on to the pres-
ent. We will definitely need software for our further work. With
the rapid development of the market of IT technologies, newer
versions of various programs have been constantly created. In
the following sections of this lesson, we will look at the basics
of constructing algorithms and installing software, which we
will use as a part of our learning process.

8
2. First View of Algorithms

2. First View
of Algorithms
The Concept of an Algorithm
We solve simple problems every day. How do we manage
to do everything? We plan our day minute by minute to make
the most of our time. We set priorities, determine the sequence
of our actions. And all this is done in order to finally get the re-
sult we need. It turns out that we are constantly confronted
with instructions, prescriptions, recipes, rules, according to
which this or that human activity occurs.
The executor of the algorithm is usually a computer, but this
is not always the case. Imagine a simple situation — cooking
breakfast. In this case, a human is the executor. What will be
his actions if he wants to cook scrambled eggs?
1. Turn on the oven;
2. Put the frying pan on the stove;
3. Pour oil in it;
4. Heat up the frying pan;
5. Break 2 eggs;
6. Fry them for 5 minutes over low heat.
Having performed this sequence of actions, we get a hot
and tasty breakfast. But what will happen if we accidentally
swap steps two and three? This will result in a dirty oven and
a bad mood for the entire day. So the algorithm is a clear
and strict sequence of actions, leading to the desired result.
Let’s imagine the work of a large plant for assembling cars for

9
Lesson 1

sale. Note that in this case the necessary result is a car and


not a throw-out. After all, it is not the result itself that matters
but its quality, meaning a properly running car. Otherwise,
the plant might be exposed to huge financial losses. The same
applies to us: nobody needs an incorrectly written algorithm.

Algorithm Properties
The algorithm is created so that the executor can follow
the instructions precisely and obtain the desired result effi-
ciently. Therefore, the algorithm has several basic requirements
in the form of its properties.
Result. First of all, when writing an algorithm, we must
aim at obtaining the desired result.
Correctness. Besides, the result should be correct (a break-
fast or a dirty stove?) After all, when the algorithm is being
compiled, we can determine the possible result in advance. If
after executing the instructions we get a result that is different
from the expected one, it is most likely that either the sequence
of actions or the actions themselves were incorrect.
Accuracy. All our actions must be specified accurately,
without double meaning. Otherwise, the executor of such
an algorithm will not understand how long it takes to fry eggs
or how many eggs to break into a frying pan.
Clarity. The algorithm’s executor must fully understand
what actions he is compelled to perform. Otherwise, such
an algorithm will be useless. Imagine that we show our reci-
pe to a foreigner. He cannot understand what we want from
him and is unable to fulfill the task assigned to him. So, it is
necessary to use one language for communication. To create

10
2. First View of Algorithms

programs in our course, you will learn C++, which contains


its own usage rules.
Discreteness. It is impossible to perform all actions at once.
First, we determine which actions are needed, and after that
we establish their sequence. More precisely, we break a big
task into subtasks. After performing one subtask, proceed to
the next, and so on.
Generality. The use of the algorithm should lead to the solu-
tion of similar, homogeneous problems. Our recipe can be used
for various types of eggs, and only the time of their cooking
is changed.
All these properties form the basis on which the algorithm
relies (Figure 1). If any of these properties are violated, there
is a high probability of creating an unstable system.

Algorithm

Result Correctness

Accuracy Clarity

Discreteness Generality

Figure 1

Types of Algorithms: Linear, Branched, Cyclic


Our life is fickle. Depending on the situation, we have to
change our plans, the sequence of our decisions. And questions
arise in our heads: what should I do in this situation? Which
path should I choose? And what will the result be?

11
Lesson 1

All the problems that we face cannot be solved in one


universal way. This is why there are three types of algorithms
in algorithmization: linear, branched, and cyclic (Figure 2).
Types of algorithms

Linear Cyclic
Branched

Figure 2

Linear. The execution of actions is carried out in a strict


order one after another. For example, a recipe for cooking
a dish in a cookbook. We always know what food to take,
how much, and what to do with it. The result of such a clear
instruction is the desired dish.
Branched. There is a choice of one of several possible
ways. Imagine a situation at home. You are lying on a couch.
It is raining outside. If the rain stops, then you go for a walk
in the fresh air, otherwise you watch TV. And, as we see,
the weather outside dictates that we can choose only one
branch of the algorithm.
Cyclic. Repeat the same actions by a given condition.
Let’s consider a scenario in the garden. A gardener needs to
fill the entire flower bed with flowers. First, he takes the first
flower. Then he digs a hole for it. He pours it with water. Next,
he places a flower in this hole and covers its roots with soil.
But this is only one flower, right?! It means that the gardener

12
2. First View of Algorithms

must repeat the same actions until he lands the entire flower


bed with flowers.
In our course, you will learn how to correctly select the order
of commands and their behavior patterns for your algorithms.
After all, the existence of an algorithm excludes the reasoning
of the executor and enables the computer to solve the problem
automatically by executing algorithm commands in the spec-
ified sequence.

13
Lesson 1

3. Graphical Description
of an Algorithm
The Concept of a Flowchart
One of the scientific studies states that in regards to the per-
ception of information, most people are visuals. That is, data
analysis is easier to study not as text but as graphics. A few
years ago, when the use of gadgets was not so popular, one of
the problems for most people was orientation on the terrain.
Sometimes one had to explain several times how to get to
the right place. In the end, the cleverest got a sheet of paper
and drew a roadmap. The use of arrows and names of streets
allowed solving this small problem.
So, the graphical method is unique in that you can
quickly determine the essence of the entire algorithm by
just looking at it. Therefore, flowcharts are used to explain
most algorithms.
A flowchart is a graphical way of describing an algorithm.
It consists of several functional blocks, and each of them fulfills
its clear purpose.

Basic Symbols in Flowcharts


The following elements are used to build flowcharts.
Arrows navigate between flowchart elements. Note that
the blocks have different numbers of inputs and outputs:
■■ Start Block — output only.
■■ End Block — input only.

14
3. Graphical Description of an Algorithm

■■ Blocks of I/O, Actions, and Cycles — one input and one


output.
■■ Conditions Block — one input and two outputs, with output
branches to be annotated (yes/no, +/–, true/false).

START/END

Linear
Branched
INPUT/OUTPUT

Cyclic
ACTION

CONDITION

LOOP
START

LOOP
END

Figure 3

Flowchart is built strictly top to bottom. It is possible to


use any number of blocks depending on the task, but the Start/
End block is allowed to be placed only twice: at the beginning
and at the end of the algorithm.
We all tried to solve rebus puzzles when we were kids. So,
at that time we were unconsciously using a simple algorithm
for their guessing. We strictly read pictures from left to right,
skipped letters where needed, followed the rules. And the re-
sult was a correct answer. Let’s take a look at the solution of
a similar rebus puzzle (Fig. 4).

15
Lesson 1

START

DETERMINE THE WORD ON THE PICTURE - CAT

REMOVE THE LAST LETTER - T

ADD THE LETTER R - CAR

THE ANSWER IS CAR

END

Figure 4

START

TRANSPORT THE GOAT

RETURN TO PICK UP THE WOLF

TRANSPORT THE WOLF AND TAKE THE GOAT

TRANSPORT THE CABBAGE

RETURN TO PICK UP THE GOAT

TRANSPORT THE GOAT

END

Figure 5

16
3. Graphical Description of an Algorithm

As you can see in the example, not all elements can be


used, but only those that are necessary to solve the algorithm.
Moreover, we determine the sequence of blocks with actions
by ourselves. And only we are the ones responsible for the cor-
rectness of the operation of this algorithm.
And now, let’s have a more complicated example. Recall
an old logical puzzle about Goat, Wolf, and Cabbage. A farmer
needs to transport all these to the opposite shore. However,
all of them cannot fit in the boat. There are only two spots in
the boat, one of them is for the farmer. And you cannot leave
the goat and the cabbage or the wolf and the goat on the shore.
Let’s make an algorithm for the farmer (Fig. 5).
As we see, we need to form a correct sequence of actions.
When performing each of these simple steps, you must im-
mediately analyze how it will affect the execution of the entire
algorithm in the future. After all, if we transported, say, cab-
bage first, and not the goat, then the farmer would no longer
have a goat. And now let’s consider another situation. A car is
driving on the road. A driver sees a traffic light in the distance.
You should determine the actions of the driver depending on
the color of the traffic light.
First, find out if there is input for the algorithm. Yes, there
is, it is the color of the traffic light.
Next, we define the output, that is, the result. In this task,
two answers are possible: continue driving or stop the car.
Therefore, it should be solved with the help of a branched
algorithm that has a choice of actions. After this choose the se-
quence of our actions in accordance with the purpose of
the blocks (Figure 6).

17
Lesson 1

START

REQUEST THE COLOR OF


THE TRAFFICT LIGHT

YES NO
IS IT GREEN?

KEEP DRIVING STOP THE CAR

END

Figure 6

It is not difficult to write these algorithms, but it is import-


ant to follow the basic rules for building flowcharts and use
the correct sequence of actions.
It is time for us to start studying the next way of describing
the algorithm — the program one. But we need to deal with
software first.

18
4. Installing Microsoft Visual Studio 2019

4. Installing Microsoft
Visual Studio 2019
Microsoft Visual Studio is a package of software products
by Microsoft, which is used for the development of various
solutions: from students’ lab researches to corporate projects.
Visual Studio includes an integrated development environment
(IDE), numerous tools, and utilities. Using Visual Studio, you can
create console applications as well as applications with complex
graphics interface. We will use Visual Studio products as a part of
our learning process. The history of Visual Studio began in 1997,
the year when Visual Studio 97 was released. You will learn to
program using Microsoft Visual Studio 2019 which is the current
version at the moment. Before we consider the installation of
Visual Studio, let us analyze an issue related to the editions of
Visual Studio. Visual Studio edition is a version of Visual Studio,
which differs from another edition with its set of features. Visual
Studio 2019 has the following editions: Enterprise, Professional,
Community. Enterprise is a complete edition of Visual Studio.
Each edition has its own pricing policy. The only exception
is Community. This is a set of Visual Studio(s) “sharpened” to
meet specific needs, for example, the development of mobile
solutions, web-based solutions, or desktop solutions, etc. You
can use Community absolutely free, including commercial
development. It is important to note that different editions
of Visual Studio are available in different languages. For in-
stance, you may want to install the Cambodian localization (if
Cambodian is your mother tongue). Do not do this! As a part

19
Lesson 1

of your future professional activity, you will meet colleagues


and projects from other countries, which certainly will use
the English interface. That is why you should always prefer
the language of the original version, which is English.

Figure 7

Figure 7.1

20
4. Installing Microsoft Visual Studio 2019

Figure 7.2

We will consider the installation of Visual Studio through


Microsoft Visual Studio 2019 Enterprise.
To start installing Enterprise, mount the ISO image using
software, such as Daemon Tools Lite, run the file vs_ultimate.
exe, and you will see the following screen (Figure 7).
Here you must complete 4 basic steps:
1. Selection of packages with software development tools.
For the training we need:
■■ Development of classic C++ applications,
■■ Development of classic .NET applications, ASP.NET ap-
plications, and development of web applications,
■■ Development for Azure,
■■ Data storage and processing.
Be careful: if you select all these packages, you will need
more than 16 GB for installation, as well as 20 GB of the disk

21
Lesson 1

space for fast work of the environment in the future. Do not


worry, it is enough for a beginner to choose Development of
classic applications in C++, the installation of which takes up
10.6 GB. And you will be able to install missing components,
language packs even later.
2. Select a set of components. The installer automatically
adds the required components.
During the training and development of applications, you
will find reference information (MSDN) by Microsoft useful.
So, it is also desirable to add it to the installation. To do this, go
to the Individual components tab and check the Help Viewer
checkbox (Figure 8).

Figure 8

The interface language for Visual Studio is determined auto-


matically. You can change it or add a new one in the Language
Packs tab. It is best to choose English, of course. First of all, it will

22
4. Installing Microsoft Visual Studio 2019

allow you to expand the vocabulary for your future specialization.


Second, it will prevent you from unnecessary and unexpected
errors when moving the project to another machine. Third, more
often than not large projects are created by a large international
team of developers, so English is good manners (Figure 9).

Figure 9

3. Set the path where to install Visual Studio.


4. Installation.
By clicking on the Install button, you confirm that you
have read and agreed to the terms and conditions of the li-
cense agreement.
You should see the installation process start. It will take
some time, during which you can track the progress. Some
windows typical for this state are provided below (Figure 10).
After the installation, if everything has been completed
successfully, you will see this window (Figure 11).

23
Lesson 1

Figure 10

Figure 11

By clicking on this button, you can run Visual Studio for


the first time or use a good old Windows interface to run
programs (Start menu, shortcuts, etc.)

24
4. Installing Microsoft Visual Studio 2019

Run Visual Studio to ensure that your previous actions were


successful. During the first start, you may be asked to specify
your Microsoft Live ID. Or you can skip this step (Figure 12).

Figure 12

To install a local copy of the reference (MSDN) by Microsoft,


you need to click on Help -> Add and Remove Help Content
(Figure 13).

Figure 13

25
Lesson 1

You will see a window allowing you to choose reference


material. We recommend choosing the Add link everywhere.
Help is never too much :) After the material selection, click
Update for local installation (Figure 14).

Figure 14

If you need to install missing components, then you just


need to start the Visual Studio Installer. It has also been fixed
on the Start menu during the installation of Visual Studio 2019.
The installation of Microsoft Visual Studio Community
2019 is very similar to the installation of Enterprise, so we
will not repeat the process here.
That is all. Now you can move on to the next sections of
this lesson and learn how to code.

26
5. The First Project

5. The First Project
A friend of mine once told me about his impressions of
visiting Prague: “If you meet a waiter, who does not speak
Russian, then take the menu and point your finger on the things
you want to order”. Sometimes similar words mean different
things. For example, the Russian word “fruit” sounds almost
like “vegetables” in Czech. Guess what the waiter will bring
if you ask him for a vegetable salad? J”.
That friend of mine wanted to warn his friends about
a possible mistake, but he would hardly be able to help if we
had to communicate with a computer instead of a waiter. Alas,
the latter does not know at what menu item you are poking
your finger. The computer thoroughly follows clear instruc-
tions. These instructions must be given by means of special
commands. The commands, in turn, make up the whole in-
dependent languages. Languages understood by the computer
are called programming languages.
Conclusion: in order to find a common language with
a Czech waiter, one has to be a ready-witted person. But
to find a common language with a computer, one must
know the language.
You already know from the first section that C++ is a pro-
gramming language. The language that allows us to explain
to the computer what we want from it. Although to be per-
fectly frank, the computer understands only one language,
i.e., the language of machine codes. Let’s take as an example

27
Lesson 1

a program that displays the phrase “Hello, world!” This is how


it looks like in the language “native” to the computer:

_YН¦ў+._5lЧ№+f-Н¦ў+ +f+ ¤д-ы+fО_fО¦¤+эm№¤+¤+¦Ф№+¤-;


- wGГ=xФ№+MZР + @ А -¦ ¦ -!+ L-!Tu ._5lЧ№+f-
&ЛZ¶QW&бфЬ№+&Л &ЛJf&ОB_Ф№+f;sЛlФ№+Л<
_t=ИФ№+_G¶u_O¶WfМ+-чfЛ№3+М-Ас°_>] Л¦Л+ЛMЛm _сбшЬ№+Л
9ШФ№+t§Л§pФ№+ш№) fd¦ +RPбшЬ№+Л 9ШФ№+tЛ§pФ№+шС) + +Э
tАс°-щЗ-Л_Ф№+f;s §lФ№+Л +u"бАФ№+¤+MАс°ЎD Аt Э+- 3+
ыўы•ы°ыЎыЇЛD$П$._4Ч№++ ._ dЛ4 Ў- ubSЛ dг4 + є --fУЙf-+
-+ЙA+@У№+Л-[Xf +tRPRVh•ў+ш_S Z+єfО-fЛцf-d¤+§ RfRfh
ш4 Л+Zы¦SшC¤д-ы¦¤+ьМ-¤++¤_e fМ+fО_fО¦f¤бЛЁdЎ
t3+ОшАс°Л§АФ№+- dб4 ЙdЙ§4 f_f _t dЛ4 Ў- uSSЛ dг4 + є
--fУЙf-+-+ЙA+@У№+Л-[ +єЙ]№fМ+fО-fЛц+ыf-d¤+§ RfRfh шз
Л+Zы+Sш¦$ PE L ¦7 р ¤! ' Р oK Р ў+

You will object that it is impossible to write programs


using such code, and you will be absolutely right! But we will
not use it. This is why we need a programming language — to
facilitate programming. Programming languages are divided
into two main groups: INTERPRETED and COMPILED.
This division relates to the specialized program that translates
commands from the programming language into the machine
language — the COMPILER or INTERPRETER. Let us find
out what the difference is between them. Imagine that we have
a file that contains a set of commands.

Scenario 1. Commands are written


in an interpreted language
Every time you start the program, the interpreter checks
the code line by line. If no syntax errors are found, the com-
mands are converted to the machine code (a set of instructions

28
5. The First Project

for the processor). The program will run for execution. If


there is an error, the interpreter will stop, and you will be
prompted to correct it and run the program again. However,
even if there are no more errors, and you have already writ-
ten the program, the interpreter will be triggered every time
you run the program in order to verify the code again. Thus,
we can conclude that the machine version of the code is not
stored anywhere. The disadvantages of this approach are
as follows: code performance is reduced, but the check is
impossible to disable.
Scenario 2. Commands are written
in a compiled language
The compiler operates almost like the interpreter, i.e.,
checks the code line by line. If it encounters an error, it does
not stop but continues examining the code to the end, revealing
all subsequent errors and generating error messages. Besides,
the compiler generates a special object file with the exten-
sion .OBJ. This file contains the program text translated into
the machine language. However, the computer does not work
directly with the file.
There is a concept of linking. A linker is another special
program that compiles the machine code (from the .OBJ
file) and various auxiliary data into a single executable file
with the extension .EXE. This file can be run for execution
as a separate, stand-alone program, and the compiler is not
involved in its launch.
The C++ language, which you are going to study, is a com-
piled language. In our case, when working with the Microsoft
Visual Studio shell, the compiler is called automatically and

29
Lesson 1

allows for quick and easy translation of C++ commands into


the machine code.
The First Attempt
One of the founders of C language, Brian Kernighan, once
said: “The only way to learn a new programming language is
by writing programs in it.” That is exactly what we are going
to do now.

Figure 15

As is customary in the world of programming, the first


program written in a new language is “Hello world!” To write
your first program, you should first run Microsoft Visual
Studio 2019. For this, go to Start -> All Programs -> Microsoft
Visual Studio 2019 or use any other method convenient to you.
After the launch, you will see something similar to the Figure
below: 15).

30
5. The First Project

Now we are going try to create a project that will become our
program eventually. We will figure out what a project is later when
we write large programs. Until then, we will think of a project
as an association of several files. Now let us do it step by step:
■■ Once you have loaded the shell, go to File->New->Project.
You will see a dialog box.
■■ The Create New Project dialog box that opens offers you
a list of languages. Select C++ and Windows Desktop Wiz-
ard as a project type (Figure 16).

Figure 16

After this, click Next.


In the next window, you should write a project name,
a path to the folder where it will be stored, a solution name
(write the project name here) (Figure 17)

31
Lesson 1

Figure 17

Next, click Create.


The project settings window will open, and we should
make sure that the project type is Console Application. Check
the field Empty Project — it means that we are creating an empty
project. Now click OK (Figure 18).

Figure 18

32
5. The First Project

So, we have prepared some space for our program. Do not


stop halfway but add an empty file to the project. We will type
the text of our program in it. To do this, follow these steps:
■■ A window titled Solution Explorer appears on the right.
If you need to call this window, use the keyboard short-
cut Ctrl+Alt+L. In this window, right-click on the folder
named Source Files.
■■ In the drop-down menu, select Add-> Add New Item...

Figure 19

■■ A file selection dialog box opens. You have lots of options


again. We recommend you select the icon C++ File (.cpp)
(a file containing a program written in C/C++).
■■ In the  text field Name (file name), enter the  file name
“Hello.” Click Add (Figure 20).

33
Lesson 1

Figure 20

After clicking on the Add button, you will see a text field


where you can type your first program.

Example of Your First Program in C++


Before you begin to write your first program, let us in-
troduce you to the concept of a comment, for the sake of
convenience. Comments are notes that are intended solely
for a programmer. The compiler ignores them. For example,
using a comment, you can describe the purpose of this or that
line in the program. The example below shows a proper way
to work with comments.
And now type the following code in the appeared text box:

// These are comments


// They are green
// Comments start with two slashes //
/* If you want to create a multi-line comment,
use the following structure */

34
5. The First Project

/* a comment */
/* This line adds the library
iostream to the program. A library is a file that
contains a description of various functions
implemented by other programmers.
The program can use functions contained in
the iostream library now */

#include <iostream>
/* C++ has a concept of namespaces.
This space defines a certain area,
at which actions of a statement or
function are aimed. In order to use a statement
located in a certain namespace, you need to
add this space to your program.
The namespace called std is added below */

using namespace std;


int main() // Start of the program, herefrom
// the program will start its execution
// The entire text of the program is placed between
// braces
{ // This is a brace
// The next line displays the greeting
// Hello, World!
// This action is carried out by cout<<
// The library and the namespace, in which
// it is located, were added to make it work

cout<<"Hello, World!\n";
// There is a semicolon at the end of the command.
// This symbol MUST end every command in C.
// return 0 to the operating system, which means
// that the program has ended without errors

return 0;
}

35
Lesson 1

As you already know, a computer understands only the lan-


guage of machine codes. So, before the program is executed by
the computer, it must be translated into the language of machine
codes. As you remember, the compiler will do it, not we. Projects
written in C++ contain a lot of files. Let us compile all files
included in the project at once. To do it, select the menu item
Build from the menu bar, then Rebuild Solution (rebuild all).

Figure 21

Figure 22

We hope you have typed the text without mistakes. Our


program has been successfully translated into the language of

36
5. The First Project

machine codes, and you can run it for execution now. Running
a program for execution is a very simple procedure. In the Debug
menu, select Start Without Debugging (Figure 22).
The program will work, and you will see a window like
this (Figure 23):

Figure 23

Congratulations! It was pretty easy, wasn’t it? To halt


the program, press any key on the keyboard (Press any key
to continue).

Opening a Saved Project


To restore a previously saved project on the disk, you
should run Visual Studio (if you have not launched it yet). Go
to the File menu, then select Open -> Project/Solution and
specify the name of your project (Figures 24 and 25).

Figure 24

37
Lesson 1

Figure 25

Once the project opens, you can continue working on it.

38
6. Data Output

6. Data Output
You already know that we can display various text lines
using the cout<< command. However, to make the compiler
understand this command, you must keep in mind the fol-
lowing main points:
1. The header of the program should contain the line
#include <iostream>

2. Before using the command, you must add a namespace,


to which the cout command belongs.
using namespace std;

3. Be sure to enclose the line you want to display using cout<<


in quotation marks. Like this:
cout<< //"write whatever you want here";

The cout<< command not only displays lines but allows


designing them. The line output is designed with special control
characters. They are a combination of the \ symbol and a charac-
ter that defines the action to be made on the line. These control
characters are called escape sequences. Here are some of them:

\b // Delete the last printed character


\n // Start a new line
\t // Go to the next tab stop
\\ // Print a backslash \
\" // Print a double quote "
\' // Print a single quote ‘

39
Lesson 1

The existence of the last three escape sequences is always


confusing at first. Why use control characters if we can simply
type: “or \ or ‘ ? The answer is in plain view: all these three
characters are also statements, and if you “simply type” them,
the compiler will take them as statements. For example, when
a word is used figuratively, it is enclosed in quotes. Suppose
you need to display the following text on the screen: “The Man
in red was “old friend” of John...".
If you do not use escape sequences, it is obvious that your
command will look like this:
cout<<"The Man in red was "old friend" of John...";

Which will lead to an inevitable error. The compiler will


perceive only a part of the line, namely cout << “The Man in
red was”. It will think that the double quotes after was is clos-
ing and assume that the rest is incorrect syntax. A program
like this will not be run for execution. The correct version is
as follows:
cout<<"The Man in red was \"old friend\" of John...";

Let’s discuss where exactly in cout<< you can specify escape


sequences. The most important thing that you need to know is
that an escape sequence must always be inside the quotation
marks because it is text, and your further possibilities are
virtually unlimited. You can do it like this:

cout<<"My name is"<<" - Ira\n ";


cout<<"I’m from Odessa\n ";
cout<<"My eyes are blue"<<"\n "<<"That’s all!!!";

40
6. Data Output

The result will be as follows:

My name is — Ira.
I’m from Odessa
My eyes are blue
That’s all!!!

Application Example of Using cout<<


Let’s write a program that displays a brief summary of
the studied escape sequences. This is what we want to see on
the screen:

\b' // Backspace
\n' // New line
\t' // Horizontal tab
\\' // Backslash \
\"' // Double quotation mark "
\'' // Single quotation mark '

Start Visual Studio 2019. Create a new project and name


it “EscapeSequences.” Type the code below.

// Header
#include <iostream>

// define the namespace that contains cout<<


using namespace std;

// Main function
int main()
{
/* The following command adds 4 tabs, prints the
Escape Sequences text, and moves to a new line
*/

41
Lesson 1

cout<<"\t\t\t\tEscape Sequences\n";
// Prints a blank line
cout<<"\n";
/* After 2 tabs, prints the text for \b, then
Backspace after another tab. Then \n moves
the output to the next line
*/
cout<<"\t\t\\b"<<"\tBackspace\n";
// Prints a blank line
cout<<"\n";
/* After 2 tabs, prints \n and
New line after 1 more tab
Then \n moves to a new line
*/
cout<<"\t\t\\n"<<"\tNew line\n";
// Prints a blank line
cout<<"\n";
/* After 2 tabs prints \t and
Horizontal tab after one more tab. Then \n moves
to a new line
*/
cout<<"\t\t\\t"<<"\tHorizontal tab\n";
// Prints a blank line
cout<<"\n";

/* After 2 tabs, prints \\ and


Backslash \ after one more tab
Then \n moves to a new line
*/
cout<<"\t\t\\\\"<<"\tBackslash \\\n";
// Prints a blank line
cout<<"\n";
/* After 2 tabs prints \" and
Double quotation mark " after one more tab
Then \n moves to a new line
*/
cout<<"\t\t\""<<"\tDouble quotation mark \"\n";

42
6. Data Output

// Prints a blank line


cout<<"\n";
/* After 2 tabs, prints \'
and Single quotation mark ' after one more tab
Then \n moves to a new line
*/
cout<<"\t\t\'"<<"\tSingle quotation mark \'\n";
// Prints a blank line
cout<<"\n";
return 0;
}

Compile the program (Build -> Rebuild Solution). If you


have many errors, remember the following rules:
■■ If the  program prints messages, then you should write
#include <iostream> and add the  namespace, to which
the  command cout (using namespace std;) belongs, at
the beginning of the program.
■■ Every program must contain a function named main().
The program starts with this function.
■■ Commands of the  main() function go inside the  curly
braces { }.
■■ All commands must end with a semicolon.
And run it (Debug -> Start Without Debugging).

P. S.
You must have noticed that we use only Latin characters
when printing data. The thing is that each character in any op-
erating system has a numerical code. And the system identifies
a character by its code. Cyrillic character codes in the console

43
Lesson 1

app under Windows do not match, so the program will not


work correctly when using the Cyrillic alphabet. For instance,
if we write in Windows:
cout<<"Утро";

This is what we get:


µЄЁю

This can be easily explained by the fact that the letter “o”


is 238 in Windows, and this number corresponds to the letter
“ю” in the console. But Latin characters match in Windows
and console. Later we will learn how to fix this.
In C++ 11, programmers were provided with a new op-
portunity to print special characters. They had to use raw
strings for that. If a string is declared as “raw,” the compiler
will interpret it character by character. To declare a string as
“raw,” use the following format.
R"(string_text)"

R indicates that it is a “raw” string. The string content must


be enclosed in brackets.
Here are some examples:

cout<<R"(hello\nworld)"; // prints hello\nworld


cout<<R"("Test 'string'\t")"; // prints "Test
// 'string'\t"
cout<<R"((These brackets))"; // prints
// (These brackets)

44
7. Data Types

7. Data Types
After you have read the previous sections of the lesson,
you can easily write a program that displays something on
the screen.

// Header
#include <iostream>

// define the namespace that contains cout<<


using namespace std;

// Main function
int main()
{
// prints "Congratulations on good start!!! :)"
// the phrase prints after 3 tabs,
// and then two blank lines are added
cout<<"\t\t\tCongratulations on"
"good start!!! :)\n\n";

return 0;
}

That is actually all that you can do (for now).


A person should never stop halfway. So, you should be
wondering how to handle data that you print. Like, how to
calculate something. Handless jugglers just do not exist,
and while some of the balls are in the air, the performer is
holding the rest in his hands. To store something (data in
particular), you need storage. RAM will be this storage for
our program. Before placing something somewhere, you

45
Lesson 1

need to pick the right package. You will unlikely, say, pour


milk into a matchbox. In programming, before you place
information in RAM, you must determine the nature of this
information. So, data types.
Data type is a concept that determines the maximum size
(in bytes) and type of information to be used by the program.
Programming partly reflects real-world objects, while
making them rather simple. At the beginning of the study,
we will face things which you have faced a lot of times. Let’s
conveniently divide all data types into the following groups:
1. Numeric.
2. Character.
3. Logical.
Next, we will look at some keywords used in the C++
language to describe data types.
Numeric Types
As you know, numbers can be integers and real. We will
call real numbers “floating-point numbers. We want to draw
your attention to the fact that the integer part is separated
from the fractional by a point, not a comma, e.g., 7.8.
Variables, wherein we will store values of real numbers,
will be declared as float or double. What is the difference
between them? The float type describes single-precision float-
ing-point numbers, and double describes double-precision
floating-point numbers. In Math, precision is determined
by the number of digits after the point. Double precision is
a method of representing numbers with doubled, compared to
a regular number of digits. Below are characteristics of types
for floating-point numbers:

46
7. Data Types

Table 1

Description Types Size in bytes


Describes single-precision real numbers float 4
Describes double-precision real numbers double 8

In addition to real numbers, C++ provides three types for


declaring integer data. The table shows the main characteristics
of these types:
Table 2

Size in
Description Types Range of values
bytes
Describes integers int 4 from -2147483648
to 2147483647
Describes short integers short 2 from -32768 to 32767
Describes long integers long 4 from -2147483648
to 2147483647
Describes long integers long 8 from –9,223,372,036,
long 854,775,808
to 9,223,372, 036,854,775,807

Character Type
The type is intended for storing only one character.
Table 3

Description Types Size in bytes


Describes characters char 1

Logical Type
The type is intended for storing logical (boolean) data.
We will look at it in detail later. Logical data can take one of
two values: true or false.

47
Lesson 1

Table 4

Size in
Description Types Values
bytes
Describes logical (boolean) values bool 1 true false

Note. If you want to exclude negative values from the data


span, write the unsigned keyword before the name of
the type. Like this: unsigned int. This type will include
only positive values from 0 to 4,294,967,294.
So, we found out what types of data exist, and which key-
words C++ uses to indicate them. In conclusion, we should
note that C++ is case-sensitive (i.e., UPPERCASE and low-
ercase letters are not the same thing). Kindly note that all of
the data types described above are lowercase. Keep a check
on it, because int is a data type, but INT is a mistake.
We will discuss the application of data types in the next
topic.

48
8. Variables and Constants

8. Variables and Constants


We have already explored data types and know how in-
formation is classified for storage. We still need to determine
how data are written in RAM and how they can be accessed
for usage or editing.
So, we agree that data that have the ability to change are
called VARIABLES, and data that do not have this ability are
CONSTANTS.
A variable is an area in RAM that has its own name and
is used to store data that can be changed.
A constant is an area in RAM that has its own name and
is used to store constant data.
Here is an example of constants: a well-known number of
days of the week and months of the year... It does not change
under any circumstances, so these values are constants.
But our age is a variable. Today a person is 26 years old,
but 27 in a year.
The definitions make it clear that data have names in order
to make it easier to find them in the memory (like things in
the baggage car are supplied with labels). In programming,
they are called identifiers. One of the first things that parents of
a newborn have to decide on is choosing a name for the baby.
Does the name leave traces on the person’s temper and fate? It
is a complex and controversial issue. You can hear absolutely
opposite opinions about it. But the fact that a name (identifi-
er) given to a new variable (constant) should be intuitive and
explain the purpose of the variable will not be disputed by
any more or less experienced programmer.

49
Lesson 1

Names are given according to the strict rules. These rules


must not be violated!
Naming Rules
Only the following characters are acceptable in names:
1. Uppercase and lowercase letters of the Latin alphabet.
And do not forget about the case-sensitivity of the lan-
guage. For instance, Age and age are two different names.
2. Digits. However, a digit cannot be used as the first char-
acter. That is, Name1 is acceptable, while 1Name is not.
3. The underscore symbol _. The thing is that space is also
a character, and this character is not valid in the name of
a variable. It is replaced by an underscore, thus improving
the readability of names. Compare: ageofman and Age_
Of_Man.
When naming a variable, remember this:
1. You cannot name a variable with keywords adopted by
the programming language. A keyword is a word that is
reserved for the programming language syntax (int, float,
double, and so on). Visual Studio highlights keywords in
blue. This will lead to confusion, at the very least.
2. The existence of two identifiers with the same name is
undesirable.
3. You cannot use any other characters, except for allowed
ones (see above).
Declaring and Using Variables and Constants
Now we have all information to create (declare) a variable.
The only things we need is to find out the general syntax:

50
8. Variables and Constants

1. data_type variable_name; — in this case, a memory cell


of the  size corresponding to the  specified type will be
provided in RAM. The name you have selected will be
assigned to this cell. What will it contain? A random num-
ber determined by the operating system will be written in
the newly created variable. This number will be stored in
the memory until you fill the variable with another value
using a special assignment operator =.
2. datatype variable_name = value; — an opportunity to
add a value to a variable upon its creation is available as
well. We call this process initialization.
3. const data_type variable_name = value; — is a constant
declaration. The  main point is that the  const keyword
goes at the beginning, regardless of the data type. Besides,
the constant must be initialized upon creation. Its value
cannot be changed later.

Printing the Value of a Variable


Printing the value of a variable is done by cout<<
cout<<variable_name; // no quotes in this case

You can display the contents of multiple variables through


<<.

cout<<variable_name1<<variable_name2;
// no quotes in this case

You can alternate the printing of the variable containing


text messages and escape sequences through cout<<”Tex-
t”<<variable_name1.

51
Lesson 1

<<"Text"<<variable_name2<<"\n";

Constants are printed just like variables.


Application Examples
Here are some examples of the creation and initialization
of variables and constants for different data types.
Integer Variables and Constants
We meet integers everywhere: age, number of seats, number
of rooms, number of days of the week, etc.
Variables that will store integers are DECLARED as follows:
int Age;

What does this line mean? It means that a variable named


Age will store an integer value. The word int declares the value
TYPE of the variable named Age.
Let’s say that now we want to add value 34 to the Age
variable. How do we do this?
Age = 34;

This line is read as follows: “Assign a value of 34 to the Age


variable.” Take a look at the assignment operator again: Age = 34.
To the left of the equal sign is the name of the variable, to which
the value is assigned. And to the right is the value that is assigned.
The constant that will store the integer is declared as follows:
const int Count_Days_in_Week = 7;

What does this line mean? The word const stresses out that
a constant is being declared. The word int says that the constant

52
8. Variables and Constants

will be an integer. This is followed by the constant name


Count_Days_in_Week and its value is equal to 7.
Let’s now analyze how to calculate the value of a variable.
What is it for? A simple example: how to calculate the number
of hours in 2000? Do you really want to calculate it on your
own? In fact, it is quite easy to have the computer do it. We
are only required to write a formula for this calculation.
2000 has 366 days, and the day has 24 hours. The formu-
la for calculating the number of hours in 2000 is as follows:
multiply 366 by 24.
C++ uses * (asterisk, Shift+8) as a multiplication sign.
Let’s develop a program that will calculate how many hours
are in 2000. Before you create a program, it is recommended
to briefly draft its algorithm.
An algorithm is a sequence of actions aimed at solving
the current problem.
Statement: there are 366 days in leap year. This value will
not change, so we declare it as an integer constant named
DayIn_2000Year. A day has 24 hours. It does not change
either. Declare it as an integer constant named HourInDay.
Our program will contain only one variable, and we will write
the result of the calculation in it. Let’s name this variable
HourIn_Year2000. It will be an integer (int).
The algorithm is as follows:
1. Declaring and initializing variables and constants.
2. Calculating the result.
3. Printing the result.
You can invent variable names yourselves (but keep in
mind the naming rules for variables).

53
Lesson 1

And now, as always, create a new project and enter the fol-


lowing code:

// Header
#include <iostream>
// define the namespace that contains cout<<
using namespace std;
// Main function
int main()
{
// prints a blank line
cout<<"\n";
// Declare integer constants
int DayIn_2000Year=366;
int HourInDay=24;
// declare an integer variable
int HourIn_Year2000;
// Calculate the desired value and
// put it in the variable HourIn_Year2000
HourIn_Year2000=DayIn_2000Year*HourInDay;
// print the value of the variable
// HourIn_Year2000
cout<<"\t\t In 2000 year "<< HourIn_Year2000;
cout<<" hours\n ";
return 0;
}

That’s it! Compile the program!


Real Variables and Constants
Example of declaration and initialization:

float Weight;
Weight=12.3452;
double weight_atom;
weight_atom= 2.5194е+017;

54
8. Variables and Constants

What does the number 2.5194е+017 mean?


It is a shorthand notation of real numbers. It is called expo-
nential notation. Here is how it is decoded. This character set
describes the number 251,940,000,000,000,000 or 2.1594×1017.
■■ 3.4Е–008 stands for 3.4×10–8, which is the same as 3.4:108.
■■ –1.5E+003 stands for –1.5×103.
Floating-point numbers of the float type may vary from
–3.4×1038 to 3.4×1038.
The values from –3.4×10–38 to 3.4×10–38 are considered to
be equal to zero.
And now let’s work with real numbers.
We will write a program to calculate the price of purchase.
Let the program use the price of an item (Cost), the amount of
purchased goods (Count), and, given the discount (Discount),
calculate the price (Price).
Create a new project Purchase and enter the text of the pro-
gram below.

// Header
#include <iostream>
// define the namespace that contains cout<<
using namespace std;
// Main function
int main()
{
// Declare the Discount variable
float Discount=0.05;

// Declare the variable
Cost float Cost=10.50;
// Declare the variable
Count int Count=5;

55
Lesson 1

// Declare the variable
Price float Price;
// Calculate the value of the Price variable
Price=Count*Cost-Count*Cost*Discount;
// Output the total price of the item considering
// the discount
cout<<"Please, pay:"<<Price<<"\n";

return 0;
}

Compile the program and run it for execution. What you


should see on the screen is shown below (Figure 26).

Figure 26

Character and Logical Variables and Constants


We will not give examples of character and logical variables
and constants in this lesson. Their purpose will be described
in more detail in the future. We will only point out their dec-
laration and initialization.

// Logical variable
bool Flag;
Flag=true;
// One character is always specified in single quotes

56
8. Variables and Constants

char Symbol='A';
/* Escape sequence is considered by the compiler as
a single character and can be accordingly written
in the variable or constant of
the char type
*/
const char NewLine='\n';
cout<<NewLine // prints a blank line

57
Lesson 1

9. Data Input
You are already familiar with the operation that displays
information on the computer screen — cout, but most pro-
grams require not only to display information on the screen
but allow entering data into the computer from a keyboard.
The previous section showed the program for calculating a dis-
count. Naturally, it would be convenient to enter parameters
such as price and quantity of the goods from the keyboard at
the stage of the program execution. Let’s see how you can do
this. If we need to enter data into the computer, we will use
the command cin. How do we use it?
The syntax of the input statement is as follows:
cin>>variable_name;

variable_name points to the variable, into which the data


entered from the keyboard must be put:
cin>>Age;

This command puts the number entered from the key-


board into the variable named Age. To enter a number into
the Number variable, just print the following command:
cin>>Number;

The input of multiple variables is as follows:

cin>>variable_name1>>variable_name2>>... >>
variable_nameN;

58
9. Data Input

The list of the variable names must contain the names of


all variables, into which you want to enter data from the key-
board. The list of names may consist of any number of variable
names separated by >>.
cin>>Quantity>>Price>>Discount;

Let’s add data input from the keyboard to the Purchase


program:

// Header
#include <iostream>
// define the namespace that contains cout<<
using namespace std;
// Main function
int main()
{
// Declare the Discount variable
float Discount=0.05;

// Declare the Cost variable


float Cost=10.50;

// Prompt to input a price of the item


cout<<"What's the cost?\n";

// Write the value in the Cost variable


cin>>Cost;

// Declare the Count variable


int Count=5;

// Prompt to input a number


cout<<"How many?\n";

// Write the value in the Count variable


cin>>Count;

59
Lesson 1

// Declare the Price variable


float Price;

// Calculate the value of the Price variable


Price=Count*Cost-Count*Cost*Discount;

// Output the total price of the item considering


// the discount
cout<<"Please, pay:"<<Price<<"\n";
return 0;
}

Now you know how the cin>> statement works. Once


the program meets this statement, it stops and waits for the user
response, until the user enters data and presses Enter. Only
after this the execution continues.
Let’s have some more practice with input and output. We
will write a cheater program: it will invite the user to play
a pick-a-number game. The rule is, whoever picks a greater
number wins.
Create a new project, name it Game, and enter this code:

// Header
#include <iostream>
// define the namespace that contains cout<<
using namespace std;
// Main function
int main()
{
// Invitation: "Let’s play!"
cout<<"Let’s play!\n";

// Declare the i variable


int i;

60
9. Data Input

// Invitation: "Enter a number"


cout<<"Enter a number:";

// Input of the number
cin>>i;

// Output the computer’s number


cout<<"I have "<<i+1<<"\n";

// Output the result of the game


cout<<"I’m winner!\n";

return 0;
}

Compile the program. Our program is easy to handle: just


enter any number, but it turns out that the computer always
picks a greater number and wins. This is what you will see
on the screen if you enter “67” after the program asks you:
“Enter a number”:

Let’s play!
Enter a number: 67 I have 68
I’m a winner!
Press any key to continue...

Why does it always win? Let’s look at the line


cout<<"I have "<<i+1<<"\n";

It outputs the value of the i variable entered from the key-


board, but increases it by 1, which means that the computer
will always output a number that is greater by 1 than that
the player has entered from the keyboard.

61
Lesson 1

If you replace i+1 with i-1, then the player will always win,
because the number displayed by the computer will always be
one less than the number entered by the player.
In conclusion, we want to draw your attention to the op-
erators + (plus) and – (minus). They are used for addition
and subtraction. C++ also has a division operator: /. This
information will be helpful in your homework assignment,
and we will talk about operators and statements in more detail
in the next lessons.

62
10. Literals

10. Literals
Literals are fixed values that the program is unable to
change. Each C++ type has a literal, including character and
boolean, integers, and floating numbers.
Some examples:
5 integer literal — int
5l l or L means long
true Boolean literal — bool
5.0 floating-point literal, is thought of as double
5.0f f or F is floating-point, is thought of as float
0.3е–2 floating-point literal «double»; e or E separate the exponential
part
'd' character literal
«Visual» string literal — a quoted set of random characters.
The compiler takes it as a set of characters and does not
execute it, even if the quotes contain some keywords or
operations.

Examples of pieces of code that contain literals.

// "abracadabra" is a string literal


// '\n' is a character literal
cout<<"abracadabra"<<'\n';
int a = 2; // 2 is a literal of the int type

The material of the first lesson ends here. We strongly


recommend you to complete your homework assignment
provided in the next section. Good luck!

63
Lesson 1

11. Homework
1. Write a program that would display a text table (use escape
sequences):

Figure 30

2. You have a TV screen diagonal in inches. Write a program


that converts this diagonal to centimeters (1 inch = 2.54
centimeters).
Below is an example that helps you check the correctness
of your program.
Input data:
The TV screen diagonal (inch) -> 42
––––––––––––––––––––––––
Output data:
The TV screen diagonal is 107 cm.

3. A battery capacity of a smartphone is N mAh. Write a pro-


gram that determines the minimum capacity of a porta-
ble charger (powerbank) if 3 full smartphone charges are
required.
Below is an example that helps you check the correctness
of your program.

64
11. Homework

Input data:
The battery capacity of the smartphone (mAh) -> 3000
––––––––––––––––––––––––––––
Output data:
The minimum capacity is 9000 mAh.

4. A hamster eats K grams of food a day. Write a program


that determines how much food in kilograms you have to
buy for 30 days.
Below is an example that helps you check the correctness
of your program.
Input data:
Food consumption per 1 day (g) -> 20
–––––––––––––––––––––––
Output data:
Amount of food for 30 days: 0.6 kg.

65
Lesson 1
Introduction to Programming

© Tatyana Lapshun
© STEP IT Academy,, www.itstep.org

All rights to protected pictures, audio, and video belong to their authors
or legal owners.
Fragments of works are used exclusively in illustration purposes to the
extent justified by the purpose as part of an educational process and
for educational purposes in accordance with Article 1273 Sec. 4 of the
Civil Code of the Russian Federation and Articles 21 and 23 of the Law
of Ukraine “On Copyright and Related Rights”. The extent and method
of cited works are in conformity with the standards, do not conflict with
a normal exploitation of the work, and do not prejudice the legitimate
interests of the authors and rightholders. Cited fragments of works can be
replaced with alternative, non-protected analogs, and as such correspond
the criteria of fair use.
All rights reserved. Any reproduction, in whole or in part, is prohibited.
Agreement of the use of works and their fragments is carried out with the
authors and other right owners. Materials from this document can be used
only with resource link.
Liability for unauthorized copying and commercial use of materials is
defined according to the current legislation of Ukraine.

You might also like