Fundamentals of Structured Programming: Lubia Vinhas March 16, 2016
Fundamentals of Structured Programming: Lubia Vinhas March 16, 2016
Fundamentals of Structured Programming: Lubia Vinhas March 16, 2016
Lubia Vinhas
This booklet contains the notes for the course CAP-390 Fundamentals of Structured Program-
ming. It is mainly based on the two books by Bjarne Stroustroup [2] [3]. I
1
2
Contents
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2 Introduction to C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.1 Standardization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.3.1 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.4 Computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.4.1 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.1 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.2 Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.3 Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Introduction
This course is about good programming, using the C++ programming language, for people
who want to become professionals (i.e. people who can produce systems that others will use),
who are assumed to be bright and willing to work hard. The students will learn fundamental
programming concepts, some key useful techniques that exist in several structured languages and
the basics of modern C++. So that after the course they will be able to write small coloquial
C++ programs, read and adapt much larger programs, learn the basics of many other languages
Our civilization runs on software. Most engineering activities involve software, but most
programs do not run on things that look like a PC with a screen, a keyboard, a box under the
table, but in aircrafts, ships, communication, phones, energy systems... and there is a lot more
of computers
refinement”
5
6
Solving a programming problem requires choosing the right concepts. All but the smallest toy
problems require di↵erent sets of concepts for di↵erent parts of the program.
what it means to perform computation and how tasks to be carried out on the computer should
Programming languages realize programming paradigms. There are many fewer programming
Most popular languages are imperative and use structured programming techniques. Struc-
tured programming techniques involve giving the code you write structures, these often involve
writing code in blocks such as sequence (code executed line by line), selection (branching
statements such as if..then..else, or case) and repetition (iterative statements such as for,
Is based on the ideas of a Von Neummann architecture. A command has a measurable e↵ect on
the program and the order of commands is important. First do this and next do that. Its
main characteristics are incremental change of the program state (variables) as a function of time;
execution of commands in an order governed by control structures; and the use of procedures,
7
abstractions of one or more actions, which can be called as a single command. Languages
1 Program Example1 ;
Var
3 Num1, Num2, Sum : I n t e g e r ;
Begin
5 Write ( ’ Input number 1 : ’ ) ;
Readln (Num1) ;
7 Write ( ’ Input number 2 : ’ ) ;
Readln (Num2) ;
9 Sum := Num1 + Num2 ;
W r i t e l n (Sum) ;
11 Readln ;
End
Based on mathematics and theory of functions. The values produced are non-mutable and time
plays a minor role compared to imperative program. All computations are done by applying
functions with no side e↵ects.Functions are firsts class citizens. Evaluate an expression and
use the resulting value for something . Representatives: Haskell, Clojure. Example in
Haskell:
The logic paradigm fits well when applied in problem domains that deal with the extraction
of knowledge from basic facts and relations. Is based on axioms, inference rules, and queries.
Program execution becomes a systematic search in a set of facts, making use of a set of inference
Data as well as operations are encapsulated in objects. Information hiding is used to pro-
tect internal properties of an object. Objects interact by means of message passing. In most
object-oriented languages objects are grouped in classes and classes are organized in inheritance
c l a s s Employee
2 {
public :
4 s t r i n g name ;
i n t age ;
6 double s a l a r y ;
};
8
Employee e1 ;
10 e1 . name = ” s o c r a t e s ” ;
e1 . age = 2 6 ;
12 e1 . s a l a r y = 1 0 0 0 ;
14 Employee e2 ;
e2 . name = ” c h i c o ” ;
16 e2 . age = 3 0 ;
e2 . s a l a r y = 5 0 0 0 ;
18
d o u b l e c o s t = e1 . s a l a r y+e2 . s a l a r y ;
There are other paradigms, such as Visual paradigm, Constraint based paradigm, Aspect-
What we have to learn to study a programming language? Syntax, semantics and how to best
use the languages features to implement the programming paradigm more adequate to solve your
problem. How many languages are out there? Which languages should I know?
Any ranking is influenced by communities of the development, investments from third parties
and ubiquitousness of projects and statistics. But this course is not about advocating the use of
this or that language. I first learnt how to program with algorithms, than I learnt PASCAL. I
work with C++, SQL and I can do a few things in PHP. I believe I can learn other languages if
I have to. I am not a radical champion for C++ or any other language. I believe that there is
Introduction to C++
Why C++? You can not learn to program without a programming language, the purpose of
a programming language is to allow you to express your ideas in code. C++ is the language
that most directly allows you to express ideas from the largest number of application areas.
Programming concepts that you learn using C++ can be used fairly directly in other languages,
http://www.cplusplus.com/info/history/.
Bjarne has written several books about programming and C++ such as the ones shown
bellow. Programming - Principles and Practices Using C++ is the one used in this course.
11
12
2.1 Standardization
The C++ Language is an open ISO-standardized language. For a time, C++ had no official
standard and was maintained by a de-facto standard, however since 1998, C++ is standardized
native code, allowing it to be one of the fastest languages in the world, if optimized. Is a
strongly-typed unsafe language, C++ is a language that expects the programmer to know
what he or she is doing, but allows for incredible amounts of control as a result.
C++ is standardized. The C++ standard was finalized and adopted by ISO (International
Organization for Standardization) as well as several national standards organizations. The ISO
standard was finalized and adopted by unanimous vote in November 1997. The latest (and
current) standard version was ratified and published by ISO in December 2014 as ISO/IEC
As one of the most frequently used languages in the world and as an open language, C++ has a
wide range of compilers that run on many di↵erent platforms that support it. Sometimes the lat-
C++ is a compiled language. That means you will need some tools to work with C++:
• Interpreter: reads a little source code, translates it to machine code, and executes it,
• Debugger: helps you step through code, shows you variables and flow of execution
• Linker: connects code from libraries with your code to make one executable
There are Integrated Development Environments (IDE) that provides editors, compilers
1. Windows:
• MingW › http://www.mingw.org/
2. Linux:
• Eclipse › http://www.eclipse.org/cdt/
• QtCreator › http://www.qt.io/ide/
3. Web based:
• CodeChef › https://www.codechef.com/ide
The purpose of learning a programming language is to become a better programmer; that is,
to become more e↵ective at designing and implementing new systems and at maintaining old
ones. The most important thing to do is to focus on concepts and not get lost in language-
technical details. This section introduces some C++ program features necessary to the most
basic programs.
14
2.3.1 Types
In typed languages, such as C++, every operation defines types of data to which an opera-
tion is applicable, with the implication that it is not applicable to other types. For example,
”this text between the quotes” is a string, and 10 is a number. In most languages the division
of a number by a string (or vice-versa) has no meaning and the compiler will reject it. This is
• built-in types: bool, char, float, int (short and long), etc.
For each type an operand have a particular semantics. The type of a variable determines
which operations are valid and what their meanings are for that type. For example:
In the computer memory, everything is just bits; type is what gives meaning to the bits. Some
types and literals in C++ can be seen in Table 2.1. An object is some memory that can hold
Type Literal
bool true, false
int 12
float 10.2 11.3
char ’c’
string "abcd"
The C++ Standard Library is a collection types and functions, which are written in the core
language and part of the C++ ISO Standard itself. It provides a ready-made set of common and
15
Declaration Memory
int i; i:
int a = 7; a: 7
int b = a; b: 7
char c = ’a’; c: ’c’
double x = 1.2; x: 1.2
string s2 = "lubia"; s2: 5 lubia
highly used features for C++. Program 5 shows a very simple using the Standard Library.
#i n c l u d e <i o s t r e a m >
2 #i n c l u d e <s t r i n g >
i n t main ( ) // r e a d f i r s t and s e c o n d name
4 {
s t d : : c o u t << ” p l e a s e e n t e r your f i r s t and s e c o n d names\n” ;
6 std : : s t r i n g f i r s t , second ;
s t d : : c i n >> f i r s t >> s e c o n d ; // r e a d two s t r i n g s
8 s t d : : s t r i n g name = f i r s t + ’ ’ + s e c on d ; // c o n c a t e n a t e
s t d : : c o u t << ” H e l l o , ”<< name << ’ \n ’ ;
10 return 0;
}
12
• comments are identified ”//” (single line) or ”/* ... */” (multiple lines).
• the main scope defines the piece of code that will be the final program.
Only lines 6 to 9 directly do anything. That’s normal. Much of the code in our programs
come from someone else (libraries). Would you rather write 1,000,000 lines of machine code?
Code that exclusively uses C++’s standard library will run on many platforms with few to no
C++ suports separate compilation, that can be used to organize a program into a set of semi-
independent fragments. An executable (final application) is the result of linking and compiling
some piece of code that has one main block of statements. Pieces of code that do not have a main
(libraries), when compiled produce object code to be linked with other code to produce a final
application. Figure 2.4 shows how is the building process happens to generate an executable
program.
C++ Linker
The interface is placed in a header file that is included by the users, whereas its imple-
mentation is defined in another file. To use a library you have to have access to its interface
files at compilation time and to its object code at linking time. Open source libraries also make
2.4 Computation
computable and how best to compute it. To do this we think about abstractions, algorithms,
heuristics, data structures. We use language to construct these ideas in terms of sequential order
of execution, expressions and statements, selection, interation, functions and data structures (for
example vectors).
17
Computation:
(input) data (output) data
code (a lot, and often messy)
• Input: data from keyboard, files, other input devices, other programs, other parts of a
program
• Computation: what our program will do with the input to produce the output
• Output: data sent to screen, files, other output devices, other programs, other parts of a
program
Computations should be expressed, correctly, simply and efficiently. To achieve that, di↵erent
strategies can be adopted, e.g., divide and conquer (breaking up big computations into many
little ones), or abstraction (provide a higher-level concept that hides details not relevant to the
problem solution). Organization of data is often the key to good code: input/output formats;
Expressions are the most basic building blocks of a program. An expression computes a
value from a number of operands. An expression produces a single value. Table 2.3 shows some
examples of expressions.
Expression Example
Literals 10, ’a’, 3.14, "Norah"
Names of variables int lenght;
Combinations perimeter = (length+width)*2;
Constant expressions constexpr double pi=3.141516;
Most Operators are conventional and you can look up details if and when you find a need.
• logical operators: == (equal), != (not equal), && (logical AND), || (logical OR)
• increment/decrement operators: ++lval, --lval, ... (lval is short for value that can
Statements are language features used to produce several values, or to do something many
Program 6 shows some computation using mathematical operators, such as +, ⇤, / and a math-
ematical function (sqrt). Program 7 also shows some computation using iteration statements.
1 // do a b i t o f v e r y s i m p l e a r i t h m e t i c :
i n t main ( )
3 {
c o u t << ” p l e a s e e n t e r a f l o a t i n g p o i n t number : ” ;
5 double n ; // f l o a t i n g p o i n t v a r i a b l e
c i n >> n ;
7 c o u t << ”n == ” << n
<< ” \nn+1 == ” << n+1 // ’ \ n ’ means a n e w l i n e
9 << ” \ n t h r e e t i m e s n == ” << 3 ⇤n
<< ” \ n t w i c e n == ” << n+n
11 << ” \nn s q u a r e d == ” << n⇤n
<< ” \ n h a l f o f n == ” << n/2
13 << ” \ n s q u a r e r o o t o f n == ” << s q r t ( n ) // l i b r a r y f u n c t i o n
<< e n d l ; // a n o t h e r name f o r n e w l i n e
15 }
i f ( a<b ) // s e l e c t i o n
2 max = b ;
else
4 max = a
int i = 0;
10 w h i l e ( i <100)
{
12 c o u t << i << ’ => ’ << s q u a r e ( i ) << ’ \n ’ ;
++i ; // i n c r e m e n t i ;
14 }
19
2.4.1 Functions
What is the name square in Program 7? It is a call to a function that was defined somewhere.
makes the program text clearer (by naming the computation), is useful in more than one place
in our program. It eases testing, distribution of labor, and maintenance of our code.
A function can not be called unless it has been previously declared. A function declaration
gives the name of the function, the type of the value returned (if any) by the function, and the
number and types of arguments that must be supplied in a call of the function(e.g. Program 8).
Program 8 Functions
1 // max . h : f u n c t i o n d e c l a r a t i o n
i n t max( i n t , i n t ) ;
3
// max . cpp : f u n c t i o n i m p l e m e n t a t i o n
5 i n t max( i n t a , i n t b ) // t h i s f u n c t i o n t a k e s 2 p a r a m e t e r s
{
7 i f ( a<b )
return b ;
9 else
return a ;
11 }
13 // main . cpp
#i n c l u d e ”max . h”
15
i n t x = max ( 7 , 9 ) ; // x becomes 9
17 i n t y = max ( 1 9 , 27) ; // y becomes 19
i n t z = max ( 2 0 , 2 0 ) ; // z becomes 20
To do just about anything of interest, we need a collection of data to work on. A data structure
is a specialized format for organizing and storing data. General data structure types include
the array, the file, the record, the table, the tree, and so on. Any data structure is designed to
organize data to suit a specific purpose so that it can be accessed and worked with in appropriate
ways.
Languages provide mechanisms to implement data structures, or libraries that provide com-
mon data structures ready to use. The C++ Standard Library includes most of the Standard
20
v.push back(4); // add an element with the value 4 at end (”the back”)
v: 2 1 4
v.push back(3); // add an element with the value 3 at end (”the back”)
v: 3 1 4 3
Template Library (STL) 1 . The STL is a generic library, meaning that its components are heavily
parameterized by a type.
Vector is the most useful STL data structure, or data container. A vector<T> holds a
sequence of values of type T (e.g. a vector named v contains 3 elements: 1, 4, 3). Figure 2.6
shows the structure of a vector and how it is built using pushback while Program 9 exemplify
1 // r e a d some t e m p e r a t u r e s i n t o a v e c t o r :
i n t main ( )
3 {
// d e c l a r e a v e c t o r o f type d o u b l e t o s t o r e t e m p e r a t u r e s
5 v e c t o r <double> temps ;
d o u b l e temp ; // a v a r i a b l e f o r a s i n g l e t e m p e r a t u r e v a l u e
7
// c i n r e a d s a v a l u e and s t o r e s i t i n temp
9 w h i l e ( c i n >>temp )
temps . push back ( temp ) ;
11 // . . . do something . . .
}
13 // c i n >>temp w i l l r e t u r n t r u e u n t i l we r e a c h t h e end o f f i l e
// o r e n c o u n t e r something t h a t i s n ’ t a d o u b l e
1 https://www.sgi.com/tech/stl/
21
A computer’s memory is a sequence of bytes. When the computer encounter a declaration such
as int var=17 it will set aside an int-size piece of memory for var somewhere and put the 17
into memory, this location has an address. Some languages, such as C++, allows you to store
and manipulate addresses. An object that store an address is called a pointer. Program 10 shows
1 int x ; // a v a r i a b l e c a l l e d x , t h a t can h o l d an i n t e g e r
x = 17; // t h e v a l u e 17 i s s t o r e d i n v a r i a b l e x
3
i n t ⇤ p i ; // a v a r i a b l e c a l l e d px t h a t can h o l d an a d d r e s s o f an
5 // i n t e g e r v a r i a b l e , o s s i m p l y a p o i n t e r t o i n t
7 p i = &x ; // t h e a d d r e s s o f x i s s t o r e d i n v a r i a b l e p i
9 // p r i n t s t h e c o n t e n t o f v a r i a b l e x
c o u t << ”x=” << x << s t d : : e n d l ;
11
// p r i n t s t h e a d d r e s s o f v a r i a b l e x
13 c o u t << ”&x=” << &x << s t d : : e n d l ;
15 // p r i n t s t h e c o n t e n t o f v a r i a b l e p i
c o u t << ” p i=” << p i << s t d : : e n d l ;
17
// p r i n t s t h e c o n t e n t o f memory p o i n t e d by p i
19 c o u t << ” ⇤ p i=” << ⇤ p i << s t d : : e n d l ;
• a pointer is a type (such as int), that provides operators suitable for addresses (whereas
• operator & retrieves the address of a variable and a pointer can hold addresses
• operator * can only be applied to pointers and retrieves the contents of the memory it
points to
A pointer is specific to the type it points to. It is not possible to assign the address of an
int to a pointer to char, because di↵erent types occupy di↵erent sizes in memory. The size
of a type is not guaranteed to be the same on every implementation of C++. Program 11 shows
When you start a C++ program, the computer set aside memory for your code (code storage),
for the global variables (static storage) and to be used when you call functions and their variables
(stack storage). The rest of the computer’s memory is potentially available for other uses: it is
the free memory. C++ makes this free storage (or heap) available through the operator new.
The new operator can allocate individual elements or sequences (arrays) of elements. In
addition of using the dereference operator (*) on a pointer we can also use the substrcipt operator
([]). It treats memory as a sequence of objects (of the type specified) with the pointer pointing
to the first one. The memory allocated can be (should be!) returned to the free store using the
1 i n t ⇤ p i = new i n t ; // a l l o c a t e one i n t
i n t ⇤ a i = new i n t [ 4 ] ; // a l l o c a t e 4 i n t s ( an a r r a y o f 4 i n t s )
3
pi = 10;
5 ai [0] = 10;
ai [1] = 20;
7 ai [2] = 30
ai [3] = 40;
9
pi: 0xAAA 10
ai: 0xBBB 10 20 30 40
23
Whenever a function needs to return a value (after some computation) it is necessary to declare
that the function return a value (declaration) and use the return statement (implementation).
Function fbyvalue in Program 13 uses the simplest way of passing an argument called called
pass-by-value. It means that the function receives a copy of the argument, so the original
variable, passed as an argument to a function is not changed by the function. Passing arguments
by value have some drawbacks, mainly the cost of copying arguments. In the example is just an
int, but if the argument is a very large data structure (for example, an image) then the function
can be costly.
In function fbyref in Program 13 it was used the way pass-by-argument. In this case, the
function receives the address of the variable passed as argument. That means that the function
can in fact change the value of the variable. Somethimes you need the best of the two ways:
preventing unecessary copies and not allowing the function to accedentally change the argument
value. In this case you should make the argument address constant as in fbyconstref.
v o i d NoRetNoArgFunc ( )
2 {
// do something and go
4 }
12 i n t f b y r e f ( i n t& x ) // pass by r e f e r e n c e
{
14 x = x+1;
return x ;
16 }
18 i n t f b y c o n s t r e f ( c o n s t i n t& x ) // pass by c o n s t r e f e r e n c e
{
20 return x ;
}
2. use pass-by-const-reference to pass large objects that you don’t neeed to modify