Lecture 2-Introduction To C++ Programming, Basic IO, and Language Translators
Lecture 2-Introduction To C++ Programming, Basic IO, and Language Translators
Lecture 2-Introduction To C++ Programming, Basic IO, and Language Translators
Introduction
C++ is a programming language. A standardized, general-purpose, object-oriented, compiled
language. C++ is accompanied by a set of functions and containers called the C++ Standard-
Library with already built functionalities or capabilities. In 1980s, Bjarne Stroustrup created C++
as an extension to a C programming language. Still, C++ evolved to be a completely different
programming language. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. C++
is currently used by Adobe, Google, Microsoft, Netflix, NASA, etc.
C++ is widely used for the so-called systems programming as well as application programming.
C++ is a language that allows us to get down to the metal where we can perform low-level routines
if needed, or build soar high applications with abstraction mechanisms such as templates and
classes. Thus, C++ is widely considered a middle-level object-oriented programming language.
Applications of C++:
C++ finds varied usage in applications such as:
Operating Systems & Systems Programming. e.g. Linux-based OS (Ubuntu etc.)
Browsers (Chrome & Firefox)
Graphics & Game engines (Photoshop, Blender, Unreal-Engine, CAD software)
Database Engines (MySQL, MongoDB, Redis etc.)
Cloud/Distributed Systems
1|Page
@myco…TCBE 2202 Computing for Civil Engineering
An IDE typically contains a source code editor, a compiler or interpreter, build automation tools
and a debugger, accessed through a single graphical user interface (GUI). The user writes and
edits source code in the code editor. The compiler translates the source code into a readable
language that is executable for a computer.
Code or Text editor: are type of programs used to edit or write code. We will use code or text-
editors to type our C++ programs. The normal extension of a text file is (.txt) but a text file
containing C++ program should be saved with ‘.CPP’ extension. Files ending with the extension
‘.CPP’, are called source code files and they are supposed to contain source code written in C++
programming language. These extension helps the compiler to identify that the file contains a C++
program. Before beginning programming with C++, one must have a code or text-editor installed
to write programs.
C++ Compiler: Once you have installed text-editor and typed and save your program in a file
with ‘.CPP’ extension, you will need a C++ compiler to compile this file. A compiler is a
computer program which converts high-level language into machine understandable low-level
language. In other words, we can say that it converts the source code written in a programming
language into another computer language which the computer understands. For compiling a C++
program we will need a C++ compiler which will convert the source code written in C++ into
machine codes.
Debugger: A debugger or debugging tool is a computer program used to test and debug other
programs (the "target" program). The main use of a debugger is to run the target program under
controlled conditions that permit the programmer to track its execution and monitor changes in
computer resources that may indicate malfunctioning code.
Note:
Testing is the process of finding errors in a program
Debugging is the process of correcting errors that are found
Bug is the error in a program e.g. Compile time errors, Runtime errors and Logical errors.
Before we start programming with C++. We will need an environment to be set-up on our local
computer to compile and run our C++ programs successfully. If you do not want to set up a local
environment you can also use online IDEs for compiling your program.
2|Page
@myco…TCBE 2202 Computing for Civil Engineering
Setting up local environment (Installing C++ IDE on Windows)
Windows Installation: There are lots of IDE available for windows operating system which you
can use to work easily with C++ programming language. One of the popular IDE is Code::Blocks.
To download Code::Blocks you may visit this link (http://www.codeblocks.org/downloads/26).
Once you have downloaded the setup file of Code::Blocks from the given link open it and follow
the instruction to install.
After successfully installing Code::Blocks, go to File menu -> Select New and create an
Empty file.
Now write your C++ program in this empty file and save the file with a ‘.cpp’ extension.
After saving the file with ‘.cpp’ extension, go to Build menu and choose the Build and Run
option.
Best C++ Integrated Development Environments (IDE) and C++ Editor for Windows & Mac OS
Examples of IDEs are listed in the table below.
Name Link
Dreamweaver https://www.adobe.com/products/dreamweaver.html
Visual Studio Code https://code.visualstudio.com/
Eclipse https://www.eclipse.org/ide/
Codelite https://codelite.org/
Atom https://atom.io/
Code::Blocks http://www.codeblocks.org/downloads/26
Dev C++ https://www.bloodshed.net/
Text editor e.g. Notepad++ https://notepad-plus-plus.org/
Source: https://www.guru99.com/best-cpp-ide-editor-free.html
Note: Visual Studio Code, Codelite, Dev C++ and Code::Blocks are some of the open source
code editors (IDE) for writing programs in C++.
Code blocks Features: It is one of the best C++ IDE for Windows, Linux, and macOS that
supports GCC (GNU Compiler Collection), Visual C++, etc.
It is one of the free C++ IDE app which provides a tabbed interface.
This C++ editor provides one of the best C++ compiler and workspace to easily combine
more than one project.
3|Page
@myco…TCBE 2202 Computing for Civil Engineering
Basic Syntax and First Program in C++
Structure of a C++ Program and the Elements of a Program
Probably the best way to start learning a programming language is by writing a program. A C++
program basically has the following components:
• Comments
• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
If you are going to construct a building, you need two things: the construction materials e.g. bricks
and a blueprint that tells you how to put them together. In computer programming you also need
two things: data (variables) and instructions (code). Variables are the basic building blocks of a
program. Instructions tell the computer what to do with the variables.
Comments are used to describe the variables and instructions. They are notes by the author
documenting the program so it is clear and easy to read. Comments are ignored by the computer.
In construction, before we can start we must order our materials: "We need 500 large bricks, 80
half-size bricks, and 4 flagstones." Similarly, in C++ you must declare all variables before you can
use them. You must name each one of your "bricks" and tell C++ what type of "brick" to use.
After the variables are defined you can begin to use them. In construction the basic structure is a
room. By combining many rooms we form a building. In C++ the basic structure is a function.
Functions can be combined to form a program.
An apprentice builder does not start out building the Empire State Building. He starts on a one-
room house. In this chapter you will concentrate on constructing simple, one-function programs.
2. #include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code
lines with expressions but indications for the compiler's preprocessor. In this case the directive
#include <iostream> tells the preprocessor to include the iostream standard file. This specific
file (iostream) includes the declarations of the basic standard input-output library in C++, and
it is included because its functionality is going to be used later in the program.
Note: The iostream is a header file that stands for input/output stream and provides basic
input/output services for the C++ program.
7|Page
@myco…TCBE 2202 Computing for Civil Engineering
3. int main ()
This line corresponds to the beginning of the definition of the main function. The main function is
the point by where all C++ programs start their execution, independently of its location within the
source code. It does not matter whether there are other functions with other names defined before
or after it - the instructions contained within this function's definition will always be the first ones
to be executed in any C++ program. For that same reason, it is essential that all C++ programs have
a main function.
The word main is followed in the code by a pair of parentheses (( )). That is because it is a function
declaration: In C++, what differentiates a function declaration from other types of expressions are
these parentheses that follow its name. Optionally, these parentheses may enclose a list of
parameters within them.
Right after these parentheses we can find the body of the main function enclosed in braces ({ }).
What is contained within these braces is what the function does when it is executed.
cout is the name of the standard output stream in C++, and the meaning of the entire statement is
to insert a sequence of characters (in this case the Hello World sequence of characters) into the
standard output stream (cout, which usually corresponds to the screen).
cout is declared in the iostream standard file within the std namespace, so that's why we needed
to include that specific file and to declare that we were going to use this specific namespace earlier
in our code.
Notice that the statement ends with a semicolon character (;). This character is used to mark the
end of the statement and in fact it must be included at the end of all expression statements in all
C++ programs (one of the most common syntax errors is indeed to forget to include some
semicolon after a statement). Note: The ; marks the end of the statement. Statements are pieces of
the C++program that get executed. Statements end with a semicolon ; in C++.
In a nutshell, the std::cout << is the natural way of outputting data to the standard output/console
window in C++. We can output multiple string literals by separating them with multiple <<
operators: e.g.
#include <iostream>
int main()
{
std::cout << "Some string." << “Another string.";
}
8|Page
@myco…TCBE 2202 Computing for Civil Engineering
To output on a new line, we need to output a new-line character \n literal. The characters are
enclosed in single quotes '\n'. Example:
#include <iostream>
int main()
{
std::cout << "First line" << '\n' << "Second line.";
}
The \ represents an escape sequence, a mechanism to output certain special characters such as new-
line character '\n', single quote character '\'' or a double quote character '\"'. Characters can also
be part of the single string literal:
#include <iostream>
int main()
{
std::cout << "First line\nSecond line.";
}
Namespaces is kind of grouping of variables under a single name. While going forward, you will
see that writing this namespace statement is useful to ease out the code.
Note: using namespace std; is used to provide standard (std) input and output namespaces. That
is, after including this statement, we do not need to write std:: before every cout and cin.
For example:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World.";
return 0;
}
9|Page
@myco…TCBE 2202 Computing for Civil Engineering
5. { and }:
The opening braces ‘{‘ indicates the beginning of the main function and the closing braces ‘}’
indicates the ending of the main function. Everything between these two comprises the body of
the main function.
6. return 0;
This is also a statement. The return statement causes the main function to finish. return may be
followed by a return code (in our example is followed by the return code with a value of zero). A
return code of 0 for the main function is generally interpreted as the program worked as expected
without any errors during its execution. This is the most usual way to end a C++ console program.
7. Indentation:
As you can see the std::cout and the return statement have been indented or moved to the right
side. This is done to make the code more readable. In a program as Hello World, it does not hold
much relevance, but as the programs become more complex, it makes the code more readable,
less error-prone. Therefore, you must always use indentations and comments to make the code
more readable.
A process return code of 0 for the main function is generally interpreted as the program
worked as expected without any errors during its execution.
Execution time simply means time taken to execute the code.
Press any key to close the console window. e.g. press Esc
In C++, output to the display console is done via "cout" and the stream insertion (or put-to) operator
<<. You can print as many items as you wish to cout, by chaining the items with the << operator.
For example,
cout << "hello" << " world, " << "again!" << endl;
Note: In C++, end1 - is used to insert a new line characters and flushes the stream.
10 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Basic I/O in C++
C++ IDEs comes with libraries which provides us with many ways for performing input and
output. In C++, input and output is performed in the form of a sequence of bytes or more
commonly known as streams. The two keywords cin and cout are used very often for taking
inputs and printing outputs respectively. These two are the most basic methods of taking input
and output in C++.
C++ being an object-oriented programming language, gives us the ability to not only define our
own streams but also redirect standard streams. Thus, in C++, a stream is an object whose
behavior is defined by a class. Thus, anything that behaves like a stream is also a stream.
Streams Objects in C++ are mainly of three types:
istream : Stream object of this type can only perform input operations from the stream
ostream : These objects can only be used for output operations.
iostream : Can be used for both input and output operations
For example:
#include <iostream>
#include: In C++, all lines that start with hash (#) sign are called directives and are processed
by a preprocessor which is a program invoked by the compiler. The #include directive tells the
compiler to include a file and #include<iostream>. It tells the compiler to include the standard
iostream file which contains declarations of all the standard input/output library functions.
Syntax:
#include< Filename >
where iostream is the name of the file to be included. The ‘<‘and ‘>’ brackets tell the compiler
to look for the file in the standard directory.
iostream:
iostream stands for standard input-output stream. This header file contains definitions of objects
like cin, cout, etc.
Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard)
to the main memory then this process is called input.
Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to
device (display screen) then this process is called output.
11 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Note: The two instances cout in C++ and cin in C++ of iostream class are used very often for
printing outputs and taking inputs respectively. These two are the most basic methods of taking
input and printing output in C++. To use cin and cout in C++ one must include the header
file iostream in the program.
int main()
{
int age;
return 0;
}
Input:
18
Output:
Enter your age:
Your age is: 21
12 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
2. Standard output stream (cout):
Usually the standard output device is the display screen. The C++ cout statement is the instance
of the ostream class. It is used to produce output on the standard output device which is usually
the display screen. The data needed to be displayed on the screen is inserted in the standard
output stream (cout) using the insertion operator (<<).
For example:
#include <iostream>
using namespace std;
int main()
{
cout << " Am a Civil Engineer!";
return 0;
}
Output:
Am a Civil Engineer!
Example:
In the following C++ Program, we read three numbers from user, and find their sum.
13 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
More Explanation on using namespace std; in C++ program
using namespace std; Is used to provide standard (std) input and output namespaces. That is,
after including this statement, we do not need to write std:: before every cout and cin.
The identifiers of the C++ standard library are defined in a namespace called std . In order to use
any identifier belonging to the standard library, we need to specify that it belongs to
the std namespace. One way to do this is by using the scope resolution operator :: .
For example,
Here, we have used the code std:: before cout . This tells the C++ compiler that the cout object we
are using belongs to the std namespace.
#include <iostream>
int main() {
std::string first_name;
return 0;
}
Run Code
Output
In the above example, we are using identifiers from the std namespace directly using the scope
resolution operator ::.
Notice that we have prefixed std:: before string, cin, cout, and endl by writing:
std::string
std::cin
std::cout
std::endl
If we remove the std:: prefix from the codes above, we will get an error.
15 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
For example,
#include <iostream>
int main() {
string first_name ;
return 0;
}
Run Code
Output
Enter your first name: Ethan
Hello Ethan!
Welcome!
In the above example, we have used the using declaration for the identifiers we want to use from
the std namespace:
using std::cout;
using std::endl;
using std::string;
Here, we are telling the compiler that we want to bring only the identifiers cout , endl ,
and string from the standard namespace to the current scope. This allows us to prevent explicitly
adding prefix std:: whenever we need to access any of those identifiers.
We can use the using directive to bring all the identifiers of the namespace std as if they were
declared globally. To do this, we utilize the using keyword. By doing this, we can:
avoid using the std:: prefix
avoid utilizing the using declaration repeatedly
For example,
#include <iostream>
// using directive
using namespace std;
int main() {
string first_name ;
return 0;
}
Run Code
Output
In the above example, we have used the using directive to bring all the identifiers of
the std namespace to our program, including the string, cout, cin, and endl identifiers.
Notes:
The using declaration only brings the specified identifiers of the namespace into the
current scope.
The using directive brings all the identifiers of a namespace into the current scope.
17 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Language Translators
Overview of Compilers and interpreters
Since computers understand only machine language, it is necessary to convert the High Level
Language (HLL) programs into machine language codes. This is achieved by using language
translators or language processors, generally known as compilers, interpreters, or assemblers
that accept statements in one language and produce equivalent statements in another language.
Therefore, regardless of what language you use, you eventually need to convert your program into
machine language so that the computer can understand it. For HLL, there are two ways to do this:
Compile the program
Interpret the program
Difference between a compiler and an interpreter.
Note: They both covert the source code in to machine codes but;
Compiler:
A compiler stores the entire high-level program, scans it, and translates the whole program into
an equivalent machine language program. During the translation process, the compiler reads the
source program and checks the syntax (grammatical) errors (Figure ‘a’). If there is any error, it
generates an error message, which is usually displayed on the screen. In case of errors, it will not
create the object code until all the errors are rectified. Figure ‘b’ below illustrates the working of
a compiler.
Once the program has been compiled, the resulting machine code is saved in an executable file,
which can be run on its own at any time.
18 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Interpreter:
It is also a language translator and translates HLL into machine language. However, unlike
compilers, it translates a statement in a program and executes the statement immediately before
translating the next source language statement (Figure below). When an error is encountered in the
program, the execution of the program is halted and an error message is displayed. Similar to
compilers, every interpreted language such as BASIC and LISP has its own interpreters.
Assembler:
As we know, assembly language is nothing more than a symbolic representation of machine code,
which allows symbolic designation of memory locations. However, no matter how close assembly
language is to machine code, the computer still cannot understand it. Therefore, the assembly
language program must be translated into machine code by a separate program called an
assembler. The assembler program recognizes the character strings that make up the symbolic
names of the various machine operations, and substitutes the required machine code for each
instruction. At the same time, it also calculates the required address in memory for each symbolic
name of a memory location, and substitutes those addresses for the names resulting in a machine
language program that can run on its own at any time. In short, it converts the assembly codes into
binary codes and then it assembles the machine understandable code into the main memory of the
computer, making it ready for execution (Figure on next page).
19 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Figure: Working of an Assembler
Note: The original assembly language program is also known as the source code, while the final
machine language program is designated as the object code. If an assembly language program
needs to be changed or corrected, it is necessary to make the changes to the source code and then
re-assemble it to create a new object program.
Thus, the Assembler translates Low level language called assembly language (2nd Generation
language).
Linker and Loader
Linker:
An application usually consists of hundreds or thousands of lines of codes. The codes are divided
into logical groups and stored in different modules so that the debugging and maintenance of the
codes becomes easier. Hence, for an application, it is always advisable to adhere to structural
(modular) programming practices. When a program is broken into several modules, each module
can be modified and compiled independently. In such a case, these modules have to be linked
together to create a complete application. This job is done by a tool known as linker. A linker is
a program that links several object modules and libraries to form a single, coherent program
(executable). Object modules are the machine code output from an assembler or compiler and
contain executable machine code and data, together with information that allows the linker to
combine the modules together to form a program.
Generally, all HLL use some inbuilt functions like calculating square roots, finding logarithm
values, etc. These functions are usually provided by the language itself, the programmer does not
need to code them separately. During the program execution process, when a program invokes any
in-built function, the linker transfers the control to that program where the function is defined, by
making the addresses of these functions known to the calling program.
Loader:
It is a part of the operating system that brings an executable file residing on disk into the memory
and starts its execution. It is responsible for loading, linking, and relocation. In computing, a loader
is a program that performs the functions of a linker and then immediately schedules the executable
code for execution, without necessarily creating an executable file as an output. It performs the
following four basic tasks:
20 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
1. Allocation: It allocates memory space for the programs.
2. Linking: It combines two or more separate object programs and supplies the information
needed to allow references between them.
3. Relocation: It prepares a program to execute properly from its storage area.
4. Loading: It places data and machine instructions into the memory.
ii. Relocating loader: It loads the program in the memory, altering the various addresses as
required to ensure correct referencing. It is a more efficient loader, but there is a slight overhead
in terms of a small delay whilst all the relative offsets are calculated. It can only relocate code that
has been produced by a linker capable of producing relative code.
21 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
a) The Preprocessor
The Preprocessor accepts source code as input and is responsible for
removing comments
Interpreting special preprocessor directives denoted by #.
For example
• #include -- includes contents of a named file. Files usually called header files. e.g.
++
Preprocessor programs provide preprocessor directives that tell the compiler to preprocess the
source code before compiling. All of these preprocessor directives begin with a ‘#’ (hash)
symbol. The ‘#’ symbol indicates that whatever statement starts with a ‘#’ will go to the
preprocessor program to get executed. Examples of some preprocessor directives
are: #include, #define, #ifndef etc. Remember that the # symbol only provides a path to the
preprocessor, and a command such as include is processed by the preprocessor program. For
example, #include will include extra code in your program. We can place these preprocessor
directives anywhere in our program.
22 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
There are 4 Main Types of Preprocessor Directives:
1. Macros:
Macros are pieces of code in a program that is given some name. Whenever this name is
encountered by the compiler, the compiler replaces the name with the actual piece of code.
The ‘#define’ directive is used to define a macro.
2. File Inclusion:
This type of preprocessor directive tells the compiler to include a file in the source code
program. There are two types of files that can be included by the user in the program:
Header files or Standard files: These files contain definitions of pre-defined functions
like cout, cin, etc.
These files must be included to work with these functions. Different functions are declared
in different header files. For example, standard I/O functions are in the ‘iostream’ file
whereas functions that perform string operations are in the ‘string’ file.
Syntax:
#include< file_name >
where file_name is the name of the file to be included. The ‘<‘ and ‘>’ brackets tell the
compiler to look for the file in the standard directory.
3. Conditional Compilation:
Conditional Compilation directives are a type of directive that helps to compile a specific
portion of the program or to skip the compilation of some specific part of the program based
on some conditions.
4. Other directives:
Apart from the above directives, there are two more directives that are not commonly
used. i.e. #undef Directive and #pragma Directive.
b) C++ Compilers
C++ programs are usually a collection of C++ code spread across one or multiple source files. The
C++ compiler compiles these files and turns them into object files. Object files are linked together
by a linker to create an executable file or a library. Some of the more popular C++ compilers are:
The C++ compiler translates source to assembly code. The source code is received from the
preprocessor.
c) Assembler
The assembler creates the object code.
23 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
d) Link Editor
If a source file references library functions or functions defined in other source files the link editor
combines these functions (with main ()) to create an executable file. External Variable references
are resolved here also.
Step 1: Write the source codes (.cpp) and header files (.h).
Step 2: Pre-process the source codes according to the preprocessor directives. Preprocessor
directives begin with a hash sign (#), e.g., #include and #define. They indicate that
certain manipulations (such as including another file or replacement of symbols) are to
be performed BEFORE compilation.
Step 3: Compile the pre-processed source codes into object codes (.obj, .o).
A given computer understands only its own machine language. Therefore, a compiler is needed to
translate a high-level language program into an equivalent machine code. A compiler checks the
source code for syntax errors, and if there are none, then it translates each instruction into one or
more machine language instructions. The machine language version is called the object code.
Step 4: Link the compiled object codes with other object codes and the library object codes
(.lib, .a) to produce the executable code (.exe).
The object code, however, may not be ready for execution. For example, it may contain references
to other programs that a user may have written or programs that the C++ compiler provides for use
by all system users. In either case, you need a linker to resolve all these external references. The
linker finds the other programs and makes them part of your program, and so produces the
executable code
Step 6: Run the executable code, with the input to produce the desired output.
Once you have compiled and linked the program, you are ready to execute the program. At this
stage all you need is select the execute option from a menu. On other systems, you must execute
the program at the command level.
24 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
The figure below illustrates the basic Process of Writing a C++ Program
25 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
7. Block: A block is a group of programming statements enclosed by braces { }. This group of
statements is treated as one single unit. There is one block in this program, which contains
the body of the main() function. There is no need to put a semicolon after the closing brace.
8. Comments: A multi-line comment begins with /* and ends with */, which may span more
than one line. An end-of-line comment begins with // and lasts till the end of the line.
Comments are NOT executable statements and are ignored by the compiler; but they provide
useful explanation and documentation. Use comments liberally.
9. Whitespaces: Blank, tab, and newline are collectively called whitespaces. Extra whitespaces
are ignored, i.e., only one whitespace is needed to separate the tokens. Nevertheless, extra
white spaces and newlines could help you and your readers better understand your
program. Use extra whitespaces and newlines liberally.
10. Case Sensitivity: C++ is case sensitive - a ROSE is NOT a Rose, and is NOT a rose.
26 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering