Programming Fundamentals
Programming Fundamentals
2
Learning outcome
❖ What you will get from the course
• Be able to describe the algorithm for your problem
• Understand and be able to use structure programming techniques
• Be able to implement a given algorithm using C++
• Understand basic concepts of Object-Oriented Programming (OOP)
• Improve your coding style
• The process of solving problem
3
Contents
❖ Basic of programming language (C++)
❖ Control structures
❖ Array and structure
❖ Pointer
❖ Recursive
❖ Class
❖ Inherirance, template, polymophism, and advanced topics
4
Syllabus
❖ Course meeting time:
❖ Lecture: 3 hours/week for 8 weeks
❖ Laboratory: 2 hours/week for 9 weeks
❖ Course mechanics:
❖ Textbook: C++ How to program
❖ Reference book: Fundamentals of C++ Programming – Richard L. Halterman
❖ Lecture notes
❖ Online materials
5
Syllabus
❖ Assessment
❖ Assignment
❖ Lab test
❖ Final exam: 90’
❖ Ratio: lab (10%), test (20%), assignment (30%), final exam (40%)
(This is a tentative ratio, it may change a bit)
❖ Coding environment:
❖ Recommend: Visual studio
❖ Other IDEs are welcome
10
Regulations
❖ Any plagiarism act will lead to zero in all tests!
❖ Final grade of assignment depends on the exam
, +
❖ A"#$%& = N ∑#*+ /0
-.
❖ Detail mapping of exam questions and assignments will be announced during the
progress of the course.
11
Hochiminh City University of Technology
Computer Science and Engineering
[CO1027] - Fundamentals of C++ Programming
2
Hardware vs. Software
❖ Hardware: physical components of computer (including peripherals)
3
Computer Architecture
❖ Computer architecture/model
• How computer runs
❖ Two types of architecture:
• von Neumann
• Harvard
4
von Neumann Architecture
❖ Created by scientist John von Neumann in 1945
keyboard mouse
2) Memory
RAM
7
von Neumann Components (cont)
3) Processor
a) Control Unit
- Manage the process Memory Process
8
von Neumann Components (cont)
4) Output
monitor printer
9
Example
Processor
CU ALU Addition
2018
Memory
2000 + 18
Software
Software
❖ Definition: A set of machine-readable instructions that directs a computer's processor
to perform specific tasks. [Wikipedia]
13
Operating system
Operating system: is the master program that manages
how software gets to use the hardware of the computer
OS
[source: Wikipedia]
Programming language
Binary code
❖ Binary code is the most basic form of software which can be executed on the
computer.
16
High-level language
C++ Python
Programming language
❖ The high-level language code is called source code.
❖ The compiled machine language code is called target code.
❖ Compiler translates the source code into target machine language.
❖ Tools for development
❖ Editor: support text editing feature for writing source code
❖ Preprocessor, compiler, linker: tools for translating source code
❖ Debugger: traces program’s execution in order to locate bugs!
❖ Profiler: collects statistics about a program’s execution
18
Programming language
❖ The process of building a computer program
Enhanced
Object code
source code
Executable
Editor Preprocessor Compiler Linker program
19
Programming language
https://fossbytes.com/programming-language-most-important-
2016-ieee/
20
Which language to use?
❖ The language must be fit-for-purpose
❖ The choice of platform is critical
❖ Existing skills of the programmers
21
Which language to use?
https://fossbytes.com/programming-language-most-important-2016-
ieee/
22
Why is C/C++?
23
[source: lifehacker]
Why is C/C++?
❖ The language that places a foundation for many others
❖ Gain high-level programming skills
❖ Freedom, flexibility, advanced techniques, …
24
Problem solving
Problem solving
❖ Think about how you solved your problems before
❖ Math, Physic, Chemistry, etc.
❖ How did you solved them?
❖ Systematic
❖ Random idea
❖ Memorising solutions
❖ Other approaches
26
Problem solving
strategies
solution
Plan Act method
28
Problem solving
❖ Two basic approaches
❖ Iterative: solve a part of the problem, repeat the process on the remaining
problem until the original problem is solved
❖ Recursive: define how to solve simplest problems. Then we break the
problem into simpler and simpler pieces until they reach the level that
computer know how to solve (by our definition).
29
Software development
❖ The software development process follows the
principles of problem solving.
❖ Various software development models existed
❖ What do you need to develop a software at the
basic level?
❖ Compiler, Debugger, Editor
❖ Integrated Development Environment (IDE)
❖ Visual Studio, Eclipse, Xcode, etc.
[source: Wikipedia]
30
Software development
❖ Address your problem, collect requirements
❖ Analyse feasible approaches, find solution
❖ Design algorithm
❖ Implement: write code
❖ Compile, debug
❖ Evaluate the program
❖ Deploy software
31
Steps in development of algorithm
❖ Problem definition
❖ Development of a model
❖ Specification of Algorithm
❖ Designing an Algorithm
❖ Checking the correctness of Algorithm
❖ Analysis of Algorithm
❖ Implementation of Algorithm
❖ Program testing
❖ Documentation Preparation
32
Algorithm
❖ Algorithm is a self-contained list of operations to be performed.
❖ An algorithm is an effective method that can be expressed within a finite
amount of space and time and in a well-defined formal language for calculating
a function.
❖ Describe algorithm
❖ Text: details of data flow and processing steps
❖ Pseudo code
❖ Flowchart
33
Algorithm
❖ Pseudo code
❖ Independent from programming language.
❖ An informal high-level description of the operating principle of
a computer program or algorithm.
34
Algorithm
❖ Pseudo code - guideline
❖ Mimic good code and natural language
❖ Consider context
35
Algorithm
❖ Flow chart
❖ A type of diagram that represents the algorithm (in
our context). The flow chart illustrates a solution
model to a given problem.
36
Algorithm
❖ Flow chart - Building blocks
37
Algorithm
❖ Flowchart
❖ Flow line: represents control pass from one symbol to another.
❖ On-page connector: has more than one arrow coming into it but only one going out. It is useful to
represent iterative processes.
38
Algorithm
❖ Flowchart
❖ Input/Output: involves receiving data and displaying processed data.
❖ Predefined process: represents complex processing steps which maybe detailed in a separate flowchart.
❖ Preparation: prepares a value for a subsequent conditional or decision step (replace decision symbol in
case of conditional loop).
39
Algorithm
Star
t
❖ Flowchart - example
Input A, B
N
B>0
Y
Y
A>B A=A-B
B=B-A
Print A
End
40
Summarise
❖ Understand concepts of Hardware/Software
❖ Understand problem solving process
❖ Definition of algorithm
❖ Role of algorithm in problem solving process
❖ Knowing how to describe an algorithm
❖ Understand concepts of pseudocode and flowchart
41
Hochiminh City University of Technology
Computer Science and Engineering
[CO1027] - Fundamentals of C++ Programming
2
“C makes it easy to shoot yourself in the foot; C++ makes it harder,
but when you do, it blows away your whole leg.”
– Bjarne Stroustrup
Today’s outline
❖ Program structure
❖ Variable and Data types
❖ Problem solving
4
Program structure
Program structure
6
Program structure
❖ Preprocessing directive: anything begin with #
❖ include: source inclusion (use libraries or additional code)
❖ define, undef, etc.: constant, macros
❖ pragma: specify diverse options for compiler
❖ main(): the entry point of our program. This is where everything start.
7
Program structure
❖ Global variables definition: these variable are visible to all classes and
functions in the program
❖ Structure, Class or Function definition and implementation
❖ Namespace: use to group components of a module, library, or a pack of
smaller libraries.
8
Using namespace
#include<iostream>
using namespace std;
int main()
{
cout << "Welcome to C++!\n";
return 0;
}
Program structure
#include <something>
// define data structure
// define functions
// declare global variables
// using namespace
int main()
{
// local variables
/* Your code should be put here.
TO DO
*/
return 0;
}
10
User IO
int main()
{
int age;
cout << "How old are you?\n";
cin >> age;
cout << "Your age: " << age << endl;
return 0;
}
Comments
❖ Two types
❖ Single line comments: anything after //
❖ a = 0; // set variable a to 0
❖ Block comments: anything between /* and */
❖ b = 1; /* set b to 1.
remember that the value variable b
can be changed later */
13
Style guide
❖ There are a number of style guides available, the best one is the one used by
the people who are paying you.
❖ A straightforward style guide is:
C++ Coding Standards
❖ For a more detailed guideline:
Google C++ Style Guideline
14
Compile the program
❖ Simplest way: using IDE
❖ Visual Studio, Xcode, KDE IDE, Eclipse, etc.
❖ Manually: gcc, g++
❖ gcc example.c
❖ g++ example.cpp
❖ Compile and link separately
❖ Use other build system: e.g. CMake
15
Variables and Data types
Variable
#include <iostream>
using namespace std;
Memory
int main() age 30
?
{
int age;
cout << "How old are you?\n";
cin >> age;
cout << "Your age: " << age << endl;
return 0;
}
17
Data types
❖ Data types in C++ is mainly divided into two types:
o Primitive Data Types: built-in or predefined data types and can be used directly by the
user to declare variables. Example: int, char , float, bool etc.
o Abstract or user defined data type: defined by user itself. Like, defining a class in C++ or
a structure.
18
Primitive Built-in Types
Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating point double
Valueless void
Wide character wchar_t
19
Memory size
Type Typical Size (in bytes) Typical Range
char 1 -127 to 127 or 0 to 255
unsigned char 1 0 to 255
signed char 1 -127 to 127
int 4 -2147483648 to 2147483647
unsigned int 4 0 to 4294967295
signed int 4 -2147483648 to 2147483647
short int 2 -32768 to 32767
unsigned short int 2 0 to 65,535
signed short int 4 -32768 to 32767
long int 4 -2,147,483,648 to 2,147,483,647
signed long int 4 same as long int
unsigned long int 4 0 to 4,294,967,295
float 4 +/- 3.4e +/- 38 (~7 digits)
double 8 +/- 1.7e +/- 308 (~15 digits)
long double 8 or 12 +/- 1.7e +/- 308 (~15 digits)
wchar_t 2 or 4 1 wide character
https://www.tutorialspoint.com/cplusplus/cpp_data_types.htm
Memory size
#include <iostream>
using namespace std;
int main() {
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
Variable declaration
❖ [optional] <type> <variable name>[<array declaration>][=assigned values]
o int i, j;
o float x = 0.5f;
o etc.
22
Variable declaration
❖ Rules for variable name (identifiers, in general):
❖ A valid identifier is a sequence of one or more letters, digits, or underscore characters (_).
❖ Case sensitive
❖ Reserved keywords:
❖ alignas, alignof, and, and_eq, asm, auto, bitand, bitor, bool, break, case, catch, char, char16_t,
char32_t, class, compl, const, constexpr, const_cast, continue, decltype, default, delete, do, double,
dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int,
long, mutable, namespace, new, noexcept, not, not_eq, nullptr, operator, or, or_eq, private, protected,
public, register, reinterpret_cast, return, short, signed, sizeof, static, static_assert, static_cast,
struct, switch, template, this, thread_local, throw, true, try, typedef, typeid, typename, union,
unsigned, using, virtual, void, volatile, wchar_t, while, xor, xor_eq
23
Output format
Output format
❖ Use escape sequences
o \n for new line
o \t for tab
25
Output format
❖ Use <iomanip> library (http://www.cplusplus.com/reference/iomanip/)
o setw(n): set the field width n to be used on output operations. By default,
setw(n) will justify everything to the right.
o Use left, right, internal to adjust to the side you want
#include <iomanip>
cout << left << setw(8) << "Name:" << "Nguyen Van An\n";
cout << left << setw(8) << "Age:" << "30\n";
cout << left << setw(8) << "Email:" << "anvn@gmail.com\n";
Output format
❖ Using cout: require “iomanip” for formatting
❖ cout.width(<output width>): set width of the output result, both text and number
❖ cout << setw(<output width>)
27
Output format
❖ Save old settings:
❖ ios::fmtflags old_settings = cout.flags();
❖ int old_precision = cout.precision();
❖ Load settings:
❖ cout.flags(new_settings);
❖ cout.precision(new_precision);
28
Output format
❖ Fixed format for floating point number
❖ cout.setf(ios::fixed, ios::floatfield);
❖ cout << fixed;
❖ E.g.:
❖ cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);
cout << 3.14159 << “, ” << 0.8642e-3;
29
Problem solving
Example problem
❖ Write a program that solve the quadratic equation (second degree
polynomial equation) of the following form:
❖ Prepare:
❖ Define problem, what are criteria and constraints?
31
Example problem
❖ Define problem:
❖ Find solution for the quadratic equation
❖ Input: constants a, b, c
❖ Output: variable x
❖ Criteria, constraints:
❖ a, b, c: integer, real, or complex numbers?
❖ x: real or complex number?
32
Example problem
❖ Gather information:
❖ known: constants a, b, c
❖ unknown: variable x
❖ Explore: existed solution!
❖ Plan: input constants, check condition, compute solution
33
Example problem
❖ Act:
❖ Write pseudocode and draw flowchart.
❖ Write the program
❖ Check:
❖ Did the program operate as designed?
❖ Is the output correct w.r.t the input?
❖ Did you test every cases?
34
Summarise
❖ Understand basic elements of C/C++
❖ Be able to read and explain the code with comments
❖ Know how to write clear code
35
Hochiminh City University of Technology
Computer Science and Engineering
[CO1027] - Fundamentals of C++ Programming
Libraries Credits: 3
Outcomes
❖ Understand basic components of C++
❖ How to use basic operators
❖ How to use libraries
❖ How to define macro, constants
2
Today’s outline
❖ Operations
❖ Libraries functions
❖ Macro definitions
4
Basic Operations
❖ Arithmetic operators: +, -, *, /, %
❖ Bitwise operators: ^, ~, &, |, >>, <<
❖ Logic operators: !, &&, ||, >, <, ==
❖ Assignment: =
5
Arithmetic operations
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
6
Example
#include<iostream>
using namespace std;
int main()
{
cout << 15 / 4 << endl;
cout << 15 / 4.0 << endl;
cout << 15 % 4 << endl;
return 0;
}
Assignment operation
Assignment operation
❖ <left operand> = <expression>
❖ return <left operand>
❖ <left operand> can’t be constant
❖ Example:
❖ pi = 3.1415;
❖ keyPressed = ‘q’;
❖ a = b = 5;
9
Assignment operation
❖ Assign at the declaration instruction:
❖ int x = 10;
❖ int y{8};
❖ float z(10.01f);
10
Example
#include <iostream>
using namespace std;
int main()
{
float width = 4.5;
float height = 5.5;
int main()
{
//Dimension of the cube
float cubeSide;
cout << "Enter the size of cube: ";
cin >> cubeSide;
//TODO
return 0;
}
Assignment operation
❖ What is the default type of constants?
❖ Can we assign different types of value to a variable?
13
Assignment operation
❖ Default type of constants depend on how you declare it
❖ 10: decimal value, default type depends on context
❖ 012: octal value
❖ 0x64: hexadecimal value
❖ 3.1415: default type is double
14
Cast operator
❖ Implicit convert the value from one type to another type
❖ (<target type>)<expression>
❖ E.g.:
❖ int a = (int)3.9583;
❖ float x = (float)a + 0.5f;
❖ double y = (double)x * (double)a;// y = x * a; is fine
15
Implicit conversion
int a = 65, integer = 80;
char charA = 65, charB = ‘B’, charC = 67;
float answer = 0, floatNumber = 0.0;
answer = floatNumber / 4;
//But assigning a float to a char doesn't quite work
charC = answer;
17
Compound assignments
Operator Example Equivalent expression
+= a += b a=a+b
-= a -= b a=a-b
*= a *= b a=a*b
/= a /= b a=a/b
%= a %= b a=a%b
18
Example
PreFix and PostFix
Incrementing Decrementing
prefix: ++a prefix: --a
postfix: a++ postfix: a--
Example
#include<iostream>
using namespace std;
int main() {
int a = 10, b = 10;
int post, pre = 0;
cout << "Inital values: \t\t\tpost = " << post << " pre= " << pre << "\n";
post = a++;
pre = ++b;
cout << "After one postfix and prefix: \tpost = " << post << " pre= " << pre << "\n";
post = a++;
pre = ++b;
cout << "After two postfix and prefix: \tpost = " << post << " pre= " << pre << "\n";
return 0;
}
C++ Standard Library
C++ Standard Library
❖ Library is the place where you implement functions, classes to serve some
specific tasks.
❖ Library contains:
❖ Definitions: constants, macro, structure, class
❖ Functions: implement specific algorithms, a unit of reusable code
❖ Class implementations
23
Library functions
❖ Function: a named sequence of code that performs a specific task
❖ Definition
❖ <return type> <function name>(<in/out parameters>);// prototype
❖ <return type> <function name>(<in/out parameters>)
{
// your implementation
}
24
C++ Standard Library
❖ Common standard libraries:
o <stdio.h>, <cstdio>
o <math.h>, <cmath>
o <string.h>, <cstring>
o <assert.h>, <cassert>
o <errno.h>, <cerrno>
o <time.h>, <ctime>
v For more detail refer to http://en.cppreference.com/w/cpp/header
25
<cstdio> library
❖ <cstdio> perform Input/Output operations:
❖ For more detail refer to http://www.cplusplus.com/reference/cstdio/
26
Output format
❖ Text output format
❖ printf(“i = %d\n”, i);
❖ cout << “i = ” << i << endl;
❖ Using function is a convenient way to format output.
❖ Using I/O streams require a bit modification in the sequence.
27
Output format
❖ printf(<format string>, arguments)
❖ Format string can contain format specifiers with the following syntax:
❖ %[flags][width][.precision][length]specifier
❖ specifier: d/i, u, o, x/X(uppercase), f/F, e/E, g/G, a/A, c, s, p, n, %(escape character)
❖ flags: +, -, space, #, 0
❖ .precision: .number, .*
❖ width: number, *
28
Output format
specifier output example
d/i signed decimal integer -2354
u unsigned decimal integer 3056
o unsigned octal 342
x/X unsigned hexadecimal integer 6f0c
f/F decimal floating point 3.14159
e/E scientific notation 3.14159e-05
g/G use shortest representation 3.14159
a/A hexadecimal floating point -0xc.90dep-3
c character a
s string damn it
p pointer address b8000000
nothing will be printed, argument must be a pointer to a signed int. The number
n
of printed characters are stored location pointed by the pointer.
% print ‘%’ character %
29
Output format
#include <stdio.h>
int main()
{
printf("Characters: %c %c \n", 'a', 65);
printf("Decimals: %d %ld\n", 1977, 650000L);
printf("Preceding with blanks: %10d \n", 1977);
printf("Preceding with zeros: %010d \n", 1977);
printf("Some different radices: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
printf("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
printf("Width trick: %*d \n", 5, 10);
printf("%s \n", "A string");
return 0;
}
30
<cstdio> library
/* gets example */
#include <cstdio>
int main()
{
char string[256];
printf("Insert your full address: ");
gets_s(string);
printf("Your address is: %s\n", string);
return 0;
}
http://www.cplusplus.com/reference/cstdio/gets/
31
<cmath> library
❖ <cmath> declares a set of functions to compute common mathematical
operations :
o Trigonometric functions (sin, cos, tan, etc)
#define PI 3.14159265
int main()
{
double param, result;
param = 30.0;
result = sin(param*PI / 180);
printf("The sine of %f degrees is %f.\n", param, result);
return 0;
}
http://www.cplusplus.com/reference/cstdio/gets/
Macro definition
Macro definition
❖ #define/#undef: preprocessor directives
❖ Extend across single line of code
❖ No semicolon “;” at the end
❖ Use “\” to write the define instruction with multiple lines
35
Macro definition
❖ Define constants: #define <identifier> <replacement>
❖ #define MAX_LENGTH 50
❖ #define MY_STRING “This is a constant string”
❖ Constants variables:
❖ const float x_2 = x / 2;// x_2 cannot be changed
36
Macro definition
❖ More examples:
❖ #define NORMALIZE_FACTOR 50
…
float fx = sum / NORMALIZE_FACTOR;
❖ #define sub(a, b) …
…
float x = 0.5 * sub(z + 3.9, y + f(t));
37
Macro definition
❖ Macros:
❖ #define sub(a, b) a - b
❖ #define sub(a, b) (a - b)
38
Example
#include <stdio.h>
int main() {
int x = 10, y = 2;
swap(int, x, y);
40
Summarise
❖ Understand basic elements of C/C++
❖ Assignment operator, default types, type casting, overflow problem
❖ Use library functions
❖ Input values
❖ Macro, constants
41
Hochiminh City University of Technology
Computer Science and Engineering
[CO1027] - Fundamentals of C++ Programming
2
File IO
File IO Steps
1. Include the <fstream> library
2. Create a stream (input, output, both):
q ifstream myfile; (for reading from a file)
q ofstream myfile; (for writing to a file)
q fstream myfile; (for reading and writing to a file)
3. Open the file myfile.open(“filename”);
4. Read or write the file
5. Close the file myfile.close();
4
ifstream
//source: http://www.cplusplus.com/reference/fstream/ifstream/open/
// print the content of a text file.
#include <iostream> // std::cout
#include <fstream> // std::ifstream
using namespace std;
int main() {
ifstream ifs;
ifs.open(“CO1011.csv", ifstream::in);
char c = ifs.get();
while (ifs.good()) {
cout << c;
c = ifs.get();
}
ifs.close();
return 0;
}
ofstream
// ofstream constructor.
#include <fstream> // std::ofstream
using namespace std;
int main() {
ofstream ofs("test.txt", ofstream::out);
ofs.close();
return 0;
}
Common functions
Open mode
member
stands for access
constant
in input File open for reading: the internal stream buffer supports input operations.
out output File open for writing: the internal stream buffer supports output operations.
binary binary Operations are performed in binary mode rather than text.
ate at end The output position starts at the end of the file.
All output operations happen at the end of the file, appending to its existing
app append
contents.
trunc truncate Any contents that existed in the file before it is open are discarded.
http://www.cplusplus.com/reference/fstream
String <string>
String input
To retrieve a string, we can use:
q gets_s() in <cstdio> (learn previous lecture)
q Or getline() in <iostream>
Example
#include<iostream>
#include<string>
using namespace std;
int main()
{
string userName;
cout << "Tell me your name? ";
getline(cin, userName);
cout << "Hello " << userName << "!\n";
return 0;
}
String functions
❖ strlen() return the length of the string
❖ strcat_s() concatenates a copy of str2 to str1
❖ strcmp() compares two strings
❖ strcpy_s() copys contents of str2 to str1
Example
/* strcat example */
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[80];
strcpy_s(str, "these ");
strcat_s(str, "strings ");
strcat_s(str, "are ");
strcat_s(str, "concatenated.");
cout<<str<<endl;
cout << "The length of the string: " << strlen(str)<<endl;
return 0;
}
Coding conversion - header files
Header files
In programming convention:
q Header files (.h) contain information about how to do a task. Header files are
declaration.
q The main program (.cpp) contains information about what to do. The cpp file
are definition.
Example
main.cpp
#include<iostream>
using namespace std;
int main()
{
cout << "Welcome to C++!\n";
return 0;
}
Example
main.cpp main.h
int main()
return 0;
}
Summary
❖ Handle with a File IO
❖ String library
❖ Coding convention – header file
18
Hochiminh City University of Technology
Computer Science and Engineering
[CO1027] - Fundamentals of C++ Programming
2
Today’s outline
❖ Relational and logical operators
❖ if-else statement
❖ Nested conditionals
❖ switch statement
❖ Enum type
3
Relational and logical operators
Relational operators
Operator Meaning
“==" Equal to
“<" Less than
“>" Greater than
“<=" Less than or equal to
“>=" Greater than or equal to
“!=” Not equal to
5
Relational operators
#include<iostream>
using namespace std;
int main() {
//instead of printing 0 and 1, create an array where
//0 = False, 1 = True
string TorF[] = { "False", "True" };
int a = 50, b = 6, c = 6;
7
Logical operators
#include<iostream>
using namespace std;
int main() {
int a = 10, b = 5, c = 10, d = 3;
std::string TorF[] = { "False", "True" };
return 0;
}
Conditional execution
❖ Boolean expression: evaluate to true/false
❖ What is true? What is false?
❖ bool type
❖ Type conversion
❖ Assignment
❖ Common expressions
9
Conditional execution
❖ Type bool: true/false
❖ Size: 1 byte (basic unit of storage)
❖ Be represented as integer: true = 1, false = 0
❖ What happens when you assign a value to boolean type:
❖ False: 0 value (for integer, floating point number, character ‘\0’)
❖ True: anything else (except structures, unless a casting operator is defined)
10
Conditional execution
❖ Examples:
❖ bool b = true, b1 = false;
int a = -1, c = 0;
float x = 0.5f, y = 1.2f;
b = a > c;
b1 = a;
b = c;
b1 = x < y && a > c;
b = x;
c = y + b1;
b1 = 50 != ‘a’;
b = x + 4.9 < y / 0.5f;
11
If-else statement
If statement
❖ Simple if statement:
❖ Execute a statement or a list of statements if the given condition is satisfied
❖ if (<conditional expression>) <statement>;
❖ if (<conditional expression>) {
<statements>
}
13
Flowchart
<exp>
N
Y
statement(s)
Statement(s)
14
Example
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter an integer: ";
cin >> number;
if (number > 0)
cout << "You entered a positive integer: " << number << endl;
15
If-else statement
❖ Full if-else statement:
❖ if (<conditional expression>) <if-true statement>;
else <if-false statement>;
❖ if (<conditional expression>) {
<if-true statements>
}
else {
<if-false statements>
}
16
Flowchart
<exp>
N
Y
if-true if-false
statement statement
statement
17
Example
#include<iostream>
using namespace std;
int main() {
int a, b, max;
cout << "Enter two integer numbers: ";
cin >> a >> b;
if (a > b)
max = a;
else
max = b;
18
Nested conditionals
❖ Nested if-else statements
❖ if (<exp>) // first check
if (<exp>) // second check
if (<exp>) // third check
<statement>
else <statement>
else <statement>
else if (<exp>) <statement>
else if (<exp>) <statement>
else <statement>
19
Nested conditionals
❖ Nested if-else statements: multi-way
❖ if (<exp 1>) <statement 1>
else if (<exp 2>) <statement 2>
else if (<exp 3>) <statement 3>
else <statement 4>
20
Example
#include<iostream>
using namespace std;
int main() {
float score;
char grade;
cout << "Enter a score [0 - 10]: ";
cin >> score;
if (score >= 8)
grade = 'A';
else if (score >= 6.5)
grade = 'B';
else if (score >= 5)
grade = 'C';
else if (score >= 4)
grade = 'D';
else
grade = 'F';
22
Example
#include<iostream>
using namespace std;
int main()
{
int a, b, max;
cout << "Enter two integer numbers: ";
cin >> a >> b;
max = (a > b) ? a : b;
25
Flowchart
statement
26
Example
#include <iostream>
using namespace std;
int main() {
char o;
float num1, num2;
switch (o) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2 << endl;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2 << endl;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2 << endl;
break;
default:
cout << "Error! operator is not correct";
break;
}
return 0;
}
27
What happens if no break statement?
❖ switch(<exp>) {
case <value 1>: <statements>;
case <value 2>: <statements>;
…
case <value N>: <statements>;
default: <statements>;
}
If break statement is not used, all cases after the correct case is executed.
28
Enumerated type
❖ Define a list of possible values of a type
❖ enum <type name> {<name of possible values>};
❖ enum [<type name>] {<name of possible values>} <variables>;
❖ Example:
❖ enum Color {Red, Orange, Yellow, Green, Blue, Violet};
Color c = Yellow;
cout << “Yellow color has value: ” << c << endl;
29
Enumerated type
❖ Define a list of possible values of a type
❖ enum <type name> {<name0 = value0>, <name1 = value1>, …};
❖ enum [<type name>] {<name0>} <variables>;
❖ Example:
❖ enum Color {Red = -1, Orange = 2, Yellow = 8, Green = 3, Blue,
Violet};
Color c = Blue;
cout << “Blue color has value: ” << c << endl;
30
Why enums are used in C++ programming?
#include <iostream>
using namespace std;
int main()
{
card = club;
cout << "Size of enum variable " << sizeof(card) << " bytes.\n";
return 0;
}
How to use enums for flags?
#include <iostream>
using namespace std;
enum designFlags {
BOLD = 1,
ITALICS = 2,
UNDERLINE = 4
};
int main()
{
int myDesign = BOLD | UNDERLINE;
cout << myDesign;
return 0;
}
Preprocessor directives
Preprocessor directives
❖ Conditional Pre-processor directives:
❖ #define, #undef, #ifdef, #ifndef, #else, #elif, #endif
❖ E.g.:
❖ int foo(float a, double b) {
#ifdef __MSC_VER
return a * 3.14159 - sqrt(b * a);
#else
return a * 3.14159 + b * b;
#endif
}
34
Preprocessor directives
❖ Conditional Pre-processor directives
❖ Library headers (*.h, *.hpp):
❖ #pragma once
// library definition
❖ #ifndef __MY_LIBRARY_H__
#define __MY_LIBRARY_H__
// library definition
#endif
35
Preprocessor directives
❖ Power of macros and preprocessor directive
❖ One definition fit all
❖ Flexible, portable
❖ Open source community
36
Indents, coding style
❖ Use indents to enhance your code
❖ Easy to manage flow of code
❖ Easy to read code
❖ Coding requires skills and the programmer, in most of cases need to follow
rules of their community.
37
Summarise
❖ Understand basic elements of C/C++
❖ Principle of conditional execution
❖ if-else statement, nested conditionals
❖ switch statement
❖ Conditional operator
38
Hochiminh City University of Technology
Computer Science and Engineering
[CO1027] - Fundamentals of C++ Programming
2
Loop statements
while statement
❖ Why do we need iterations?
❖ Waiting for something to happen
❖ Operate on several objects
❖ List, array of objects
❖ String
4
while loop
❖ Syntax:
❖ while (<condition>) <statement>;
❖ while (<condition>) {
<statements>;
}
5
while loop
❖ Flowchart
<cond.>
N
Y
statement(s)
statement(s)
6
Example
#include<iostream>
using namespace std;
int main() {
int counter = 0;
while (counter < 10) {
cout << counter << " ";
counter++;
}
cout << endl;
return 0;
}
Do-while loop
❖ Syntax:
❖ do <statement> while (<condition>);
❖ do {
<statements>;
} while (<condition>);
8
Do-while loop
❖ Flowchart
statement(s)
Y
<cond.>
statement(s)
9
Example
#include<iostream>
using namespace std;
int main() {
int counter = 0;
do {
cout << counter << " ";
counter++;
} while (counter < 10);
cout << endl;
return 0;
}
while statement
❖ Note:
❖ Remember to initialize variables in the condition expression before
entering the while statement (at least you know what will happen when
you check the condition).
❖ Do not forget stopping condition.
❖ Take care of counters.
11
for statement
❖ Why do you need for statement?
❖ Just another way to write iteration/loop structure!
❖ Counting is a frequent activity
❖ for: a specialised loop that package the following tasks in a statement
❖ Initialise a counter variable
❖ Modify the counter
❖ Check complete condition
12
for statement
❖ for loop:
❖ for (<initialization>; <condition>; <modification>) <statement>;
❖ for (<initialization>; <condition>; <modification>) {
<statements>;
}
13
for statement
❖ Flowchart
initialization
<cond.>
N
modification Y
statement(s)
statement(s)
14
for statement
❖ Initialization: set value for the counter
❖ Declare one or many counters (same type) and init them at once
❖ Initialize many counters if needed
❖ Condition: a boolean expression that must be evaluated at each loop
❖ Modification: change value of the counter at each loop
15
Example
#include<iostream>
using namespace std;
int main() {
for (int i = 0; i < 10; i++)
cout << i << " ";
16
for statement
❖ Note that initialization and modification can contain multiple statements
separated by commas.
#include <iostream>
using namespace std;
int main() {
int i, j;
for (i = 5, j = 10; i + j < 20; i++, j++) {
cout << "i + j = " << (i + j) << '\n';
}
return 0;
}
Infinite loops
while (100) {
}
while (true) {
}
do {
} while (-20);
for (;;) {
}
18
Exist loops
❖ The two most commonly used are:
❖ break: will end the loop and begin executing the first statement that comes
AFTER the end of the loop.
❖ continue: force the next iteration to be executed.
Example
#include <iostream>
using namespace std;
int main() {
int count;
for (count = 1; count <= 10; count++) {
if (count == 5)
break;
cout << count << " ";
}
cout << "\nBroke out of loop at count = " << count << endl;
return 0;
}
Example
#include <iostream>
using namespace std;
int main() {
int count;
for (count = 1; count <= 10; count++) {
if (count == 5)
continue;
cout << count << " ";
}
22
Example
#include <iostream>
using namespace std;
int main() {
int i, j;
return 0;
}
Structure programming
Structure programming
❖ Definition: a programming paradigm aimed at improving the clarity, quality
and development time of a computer program by making extensive use of
subroutines, block structures and for/while loops
❖ Structured programming languages: ALGOL, Pascal, PL/I, Ada, C/C++, etc.
25
Structure programming
❖ Loop and array
❖ Loop is good for performing operations on arrays, strings.
❖ “while”, “do-while”, “for” are exchangeable.
❖ Fixed size data should be processed using finite loops.
26
Problem solving - example
❖ Input and draw the following figure in terminal:
❖ Input: N (number of lines)
❖ Output: (in case N = 5)
*
* *
* * *
* * * *
* * * * *
27
Problem solving - example
❖ Input and draw the following figure in terminal:
❖ Input: N (number of lines)
❖ Output: (in case N = 5)
* *
** **
*** ***
**** ****
*********
28
Problem solving - example
❖ Input and draw the following figure in terminal:
❖ Input: N (number of lines)
❖ Output: (in case N = 5)
* *
** **
* * * *
* * * *
* * *
29
Summarise
❖ Understand loop structures: while, do-while , for
❖ Implements algorithms with loops
30
Hochiminh City University of Technology
Computer Science and Engineering
[CO1027] - Fundamentals of C++ Programming
2
Today’s outline
❖ Structured data types
❖ Array
❖ Structure
❖ Pointer
❖ Dynamic memory
3
Structured data types
Structured data types
❖ Can we implement a program with only basic data types?
❖ What do we need beside basic data types?
❖ A sequence of memory slots that contains a specific data type
❖ A mixture of different data types
5
Array
Array
7
Declaring Arrays
❖ <type> arrayName [ arraySize ];
❖ E.g: int c[5];
0 1 2 3 4
c
int
8
Initializing Arrays
❖ One by one
❖ E.g: c[4] = 10;
❖ Using a loop
❖ E.g: for (int i = 0; i < 5; i++) c[i] = 0;
❖ Declaring with an initializer list
❖ E.g: int c[5] = { 10, 20, 30, 40, 50 };
9
Accessing the values of an array
❖ The values of any of the elements in an array can be accessed just like the
value of a regular variable of the same type. The syntax is:
❖ name[index]
❖ Example:
int a = 2;
c[0] = a;
c[a] = 75;
b = c[a + 2];
c[c[a]] = c[2] + 5;
Example
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
int c[10];
for (int i = 0; i < 10; i++) c[i] = 0;
return 0;
}
Example
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
int c[10] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
return 0;
}
Structure
Structure
❖ Structure is user defined data type which allows you to combine data items
of different kinds.
❖ Structures are used to represent a record.
Books
q Title
q Author
q Subject
q Book ID
14
Defining a Structure
15
Example
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
typedef struct {
char title[50];
char author[50];
char subject[100];
int book_id;
} Books;
Books book1;
Accessing Structure Members
❖ Using the member access operator (.)
// book 1 specification
strcpy_s(Book1.title, "Learn C++ Programming");
strcpy_s(Book1.author, "Chand Miyan");
strcpy_s(Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
https://www.tutorialspoint.com/cplusplus/cpp_data_structures.htm
18
Pointer
Pointer
❖ Pointer variables contain memory addresses as their values
20
Declaring Pointers
❖ Direct way:
❖ <type> * <identifier>;
❖ E.g.: int * a;
❖ Using typedef keyword:
❖ typedef <type>* <alias_type>;
❖ E.g.:
typedef int * intPointer;
intPointer a;
21
Using Pointers
❖ Defining a pointer variable
int var = 20; // actual variable declaration.
int *ip; // pointer variable
❖ Assigning the address of a variable to a pointer
ip = &var; // using address operator &
❖ Accessing the value at the address available in the pointer variable
cout << *ip << endl; // using dereferencing operator *
*ip = 5;
NULL Pointers
❖ Assigning the pointer NULL to a pointer variable in case you do not have
exact address to be assigned.
int *ptr = NULL;
if(ptr == NULL)
Or
if(!ptr)
Using const with Pointers
❖ Nonconstant Pointer to Nonconstant Data
❖ Nonconstant Pointer to Constant Data
❖ Constant Pointer to Nonconstant Data
❖ Constant Pointer to Constant Data
Using const with Pointers
❖ Nonconstant Pointer to Nonconstant Data
❖ the data can be modified through the dereferenced pointer
❖ the pointer can be modified to point to other data
int a = 5;
int b = 9;
int *ptr = &a;
*ptr = 6; // OK
ptr = &b; // OK
Using const with Pointers
❖ Nonconstant Pointer to Constant Data
❖ the data can NOT be modified through the dereferenced pointer
❖ the pointer can be modified to point to other data
const int a = 5;
int b = 9;
const int *ptr = &a;
*ptr = 6; // Error
ptr = &b; // OK
Using const with Pointers
❖ Constant Pointer to Nonconstant Data
❖ the data can be modified through the dereferenced pointer
❖ the pointer can NOT be modified to point to other data
int a = 5;
int b = 9;
int* const ptr = &a;
*ptr = 6; // OK
ptr = &b; // Error
Using const with Pointers
❖ Constant Pointer to Constant Data
❖ the data can NOT be modified through the dereferenced pointer
❖ the pointer can NOT be modified to point to other data
const int a = 5;
const int b = 9;
int* const ptr = &a;
*ptr = 6; // Error
ptr = &b; // Error
Pointer Arithmetic
❖ Four arithmetic operators that can be used on pointers: ++, --, +, and -
30
Pointers vs Arrays
❖ Arrays and pointers are intimately related in C++ and may be used almost
interchangeably.
int var[MAX] = { 10, 100, 200 };
int *ptr;
31
Example
#include <iostream>
using namespace std;
const int MAX = 3;
int main() {
int var[MAX] = { 10, 100, 200 };
int *ptr;
int main() {
const char *names[MAX] = { "An Nguyen", "Binh Tran", "Cong Pham", "Dat Le" };
return 0;
}
https://www.tutorialspoint.com/cplusplus/cpp_array_of_pointers.htm
Pointer to Pointer
https://www.tutorialspoint.com/cplusplus/cpp_pointer_to_pointer.ht
m
Example
#include <iostream>
int main() {
int var = 300;
int *ptr = &var; // take the address of var
int **pptr = &ptr; // take the address of ptr
return 0;
}
https://www.tutorialspoint.com/cplusplus/cpp_pointer_to_pointer.ht
m
References
❖ A reference variable is an alias, that is, another name for an already existing
variable.
int a = 10;
int& b = a;
❖ References are usually used for function argument lists and function return
values.
https://www.tutorialspoint.com/cplusplus/cpp_references.htm
36
Example
#include<iostream>
using namespace std;
int main() {
int a = 10;
int& b = a;
cout << "Value of a :" << a << endl;
cout << "Value of a reference :" << b << endl;
a = 6;
cout << "Value of a :" << a << endl;
cout << "Value of a reference :" << b << endl;
}
Pointers vs References
❖ Three major differences between references and pointers:
q You cannot have NULL references. You must always be able to assume
that a reference is connected to a legitimate piece of storage.
q Once a reference is initialized to an object, it cannot be changed to refer to
another object.
q A reference must be initialized when it is created. Pointers can be
initialized at any time. Pointers can be pointed to another object at any
time.
Dynamic Merory
Allocating Dynamic Memory
❖ Dynamic memory is allocated using operator new. Here is the syntax:
q <pointer> = new <type>
q <pointer> = new <type> [<number_of_elements>]
❖ Examples:
q int * a = new int[5];
int
Releasing Dynamic Memory
❖ Dynamic memory is released using operator delete. Here is the syntax:
q delete <pointer>
q delete [] <pointer>
❖ Examples:
q delete []a;
Summarise
❖ Structured data types
❖ Array
❖ Structure
❖ Pointer
❖ Dynamic memory
42
Hochiminh City University of Technology
Computer Science and Engineering
[CO1027] - Fundamentals of C++ Programming
2
Outline
❖ Function: definition, declaration, parameters, returned value
❖ Scope of variables
❖ Storage
3
Function
Function
❖ You should never write monolithic code
❖ Difficult to write correctly.
❖ Difficult to debug.
❖ Difficult to extend.
❖ Hard to maintenance
❖ Non-reusable
❖ Nonsense!
5
Function
❖ Definition: a group of statements that is given a name, and which can be called from
some point of the program.
Input
Function
Output
❖ All C++ functions (except the special case of the main function) should have:
q A declaration: this is a statement of how the function is to be called.
q A definition: this is the statement(s) of the task the function performs when called
Function Declaration
❖ A function is declared with the syntax:
returnVariableType functionName(parameter1, parameter2,
...,parameterN);
❖ Note the semi-colon at the end of the statement.
Function Definition
❖ A function is defined with the syntax:
retVariableType functionName(parameter1, parameter2,
...,parameterN)
{
statement(s);
}
Function
❖ C++ functions can:
q Accept parameters, but they are not required
q Return values, but a return value is not required
q Can modify parameters, if given explicit direction to do so
9
Function: No Return, No Parameters
#include<iostream>
using namespace std;
void displayMessage();
int main() {
displayMessage();
return 0;
}
void displayMessage() {
cout << "Welcome to CO1011!\n";
}
10
Functions with Parameters
#include<iostream>
using namespace std;
int main() {
displaySum(5, 10);
return 0;
}
11
Functions with Return
#include<iostream>
using namespace std;
int main() {
int sum = computeSum(5, 10);
printf("%d + %d = %d\n", 5, 10, sum);
return 0;
}
13
Pass Parameters
❖ Parameters: there are two ways to pass parameters to a function
❖ Value: the value will be copied to local variable (parameter) of the function
❖ Reference (only in C++): the parameter is associated with passed variable
❖ Passing by reference refers to passing the address of the variable
❖ Any change in the parameter affects the variable
14
Example
#include<iostream>
using namespace std;
void increment(int &input);
int main() {
int a = 34;
cout << "Before the function call a = " << a << "\n";
increment(a);
cout << "After the function call a = " << a << "\n";
return 0;
}
int main() {
const int size = 3;
int array[size] = { 33,66,99 };
arrayAsPointer(array, size);
return 0;
}
int main() {
cout << "The default box volume : " << computeBoxVolume() <<endl;
cout << "The second box volume : " << computeBoxVolume(10) << endl;
}
20
Example
float add(float a, float b);
int add(int a, int b);
double add(int a, double b);
24
Scope of Variables
#include<iostream>
using namespace std;
int main() {
cout << "global x = " << x << endl;
int y = 7; // local variable;
cout << "local y in main's scope = " << y << endl;
25
Unary Scope Resolution Operator
❖ It’s possible to declare local and global variables of the same name.
❖ Local variables take precedence over global variables
❖ The scope resolution operator :: is used to access to the global variable.
26
Example
#include<iostream>
using namespace std;
int main() {
int num = 10; //local variable
cout << "Local variable num = " << num << endl;
cout << "Global variable num = " << ::num << endl;
return 0;
}
27
Storage
Storage
❖ How your program is organized?
❖ What are common errors?
29
Storage
high address
command line arguments
////
and environment variables
stack
heap
initialized data
read from program file
text (code segment)
low address
30
Storage
❖ Code segment: contains executable code (binary code)
❖ Data segment:
❖ Initialized data: global, static, constants
❖ Uninitialized data
❖ Heap: contains allocated memory at runtime
❖ Stack: stores local variables, passed arguments, and return address
31
Function Call
#include <iostream>
using namespace std;
int main() {
int a = 10;
cout << a << " squared: " << square(a) << endl;
return 0;
}
int square(int x) {
return x * x;
}
Function Call
Function Call
Function Call
Storage
❖ Common errors:
❖ Use variables without initialization
❖ Memory fault
❖ Access restricted areas
❖ Memory corruption
36
Uninitialized variables
#include <iostream>
#include <math.h>
using namespace std;
float val;
int main() {
float x, y;
x = 0.5f;
cout << foo(x, y) << endl;
return 0;
}
37
Memory fault (access freed memory)
#include <iostream>
#include <math.h>
using namespace std;
int main() {
float x, y;
x = 0.5f;
y = 3.9f;
float *pRet = foo(x, y);
cout << *pRet << endl;
return 0;
}
38
Memory corruption
#include <iostream>
#include <math.h>
int main() {
char pStr [] = "This string will overwrite the local buffer";
foo(pStr);
return 0;
}
39
Summarise
❖ Learn about functions: how to define and use in the program
❖ How to pass parameters, understand scope of variables
❖ Memory organization of a program
40
Hochiminh City University of Technology
Computer Science and Engineering
[CO1027] - Fundamentals of C++ Programming
2
Outline
❖ Recursion
3
Recursion
Recursion
❖ Problem solving methods
❖ Principle: divide the big problem into smaller problems
❖ Recursivity is a property that function have to be called by themselves.
❖ Principle: define the solution of big problem using the solution of smaller
problems. A set of base solution must be defined
5
Recursion
❖ Factorial function: f(n) = n!
❖ 0! = 1
❖ f(n) = f(n - 1) * n
❖ Fibonacci sequence is defined as follows
❖ F(1) = F(2) = 1
❖ F(n) = F(n - 1) + F(n - 2)
6
Recursive termination
❖ A recursive termination is a condition that, when met, will cause the
recursive function to stop calling itself.
❖ Factorial function: f(n) = n!
❖ 0! = 1 (recursive termination)
❖ f(n) = f(n - 1) * n
Example
#include<iostream>
using namespace std;
int main() {
cout << factorial(5) << endl;
return 0;
}
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
Example
#include<iostream>
using namespace std;
int main() {
cout << fibonacci(5) << endl;
return 0;
}
int fibonacci(int n) {
if (n <= 2) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
Indirect Recursion
#include <iostream>
using namespace std;
int fa(int);
int fb(int);
int main() {
int num = 5;
cout << fa(num) << endl;
return 0;
}
int fa(int n) {
if (n <= 1) return 1;
else return n * fb(n - 1);
}
int fb(int n) {
if (n <= 1) return 1;
else return n * fa(n - 1);
}
Recursion
❖ Type of recursions
❖ Tail recursion: nothing has to be done after the call return
❖ Head recursion: the first statement in function is a recursive call
❖ Middle / multi-recursion
❖ Mutual recursion: function X and Y are mutually-recursive if function X
calls function Y, and function Y in turn call function X. This is called
indirect recursion
11
Recursion vs. Iteration
Recursion vs. Iteration
❖ We can always solve a recursive problem iteratively!
❖ Iterative functions are almost always more efficient than their recursive
counterparts.
❖ Why do we need recursion?
❖ much simpler to write
❖ much cleaner and easier to follow
13
When to choose recursion
❖ In general, recursion is a good choice when most of the following are true:
q The recursive code is much simpler to implement.
q The recursion depth can be limited (e.g. there’s no way to provide an input
that will cause it to recurse down 100,000 levels).
q The iterative version of the algorithm requires managing a stack of data.
q This isn’t a performance-critical section of code.
Recursion
❖ More examples
❖ Simple: print a string backward
❖ Classic: Hanoi tower
15
Summarise
❖ Recursion technique
16
Hochiminh City University of Technology
Computer Science and Engineering
[CO1027] - Fundamentals of C++ Programming
2
Outline
❖ Class:
❖ Concept and definition
❖ Encapsulation
❖ Constructor/Destructor
3
Structure versus Object-Oriented Programming
❖ Structure programming focuses on the process/actions that occur in a
program. The program starts at the beginning, does something, and ends.
7
Terminologies
❖ Object is an instant of a particular class
❖ Data are known as fields, members, attributes, or properties
❖ Functions are known as methods
Classes and Objects
❖ A Class is like a blueprint and objects are like houses built from the blueprint
Features
❖ Encapsulation (hiding data): allows the programmer to group data and the
subroutines that operate on them together in one place, and to hide irrelevant
details from the user.
❖ Inheritance: allows code to be reused between related types.
❖ Polymorphism: allows a value to be one of several types, and determining at
runtime which functions to call on based on its type.
10
Encapsulation
❖ Packaging related stuff together
❖ User need to know only public methods/data of the object: interface
❖ Interfaces abstract away the details of how all the operations are performed
❖ “Data hiding”, “black box”.
11
Class Declaration
class <Class_Name>
{
<access_specifier>:
member declaration;
...
<access_specifier>:
member declaration;
...
};
12
Class Example
class Rectangle
{
private:
double width;
double height;
public:
void setWidth(double);
void setHeight(double);
double getWidth();
double getHeight();
double getArea();
};
Class Access specifier
❖ Used to control access to members of the class:
❖ private (default) : the members declared as private are only accessible from
within the class. No outside Access is allowed.
❖ public: the members declared as public are accessible from outside the
Class through an object of the class.
❖ Can be listed in any order in a class
❖ Can appear multiple times in a class
14
Member Function Definition
❖ When defining a member function:
❖ Put prototype in class declaration
❖ Define function using class name and scope resolution operator (::)
void Rectangle::setWidth(double w)
{
width = w;
}
Declaration vs Definition
❖ Separate the declaration (specification) part from the definition
(implementation) part.
❖ Place class declaration in a header file. E.g. Rectangle.h
❖ Place member function definitions in *.cpp file. E.g. Rectangle.cpp. This file
must #include the class specification file.
❖ Programs that use the class must #include the class specification file.
Set and Get
❖ Set (mutator): a member function that stores a value in a private member
variable, or changes its value in some way.
void setWidth(double);
void setHeight(double);
19
Static Class Members
❖ Static data members: are considered as “class” variables since they are
common variables for all objects of the same class.
❖ Need to be initialized somewhere outside the class
❖ Can be accessed through object or class
❖ Example: object counter
❖ Static function members: can only access static members of the class.
20
Constructor vs Destructor
Constructor
❖ Constructors: a special function that is automatically called whenever a new
object is created .
❖ allow the class to initialize member variables or allocate storage.
❖ do not return a value, including void.
❖ can not be called explicitly as member functions.
22
Default Constructor
❖ A default constructor is a constructor that takes no arguments.
❖ If you write a class with no constructor at all, C++ will write a default
constructor for you, one that does nothing.
❖ A simple instantiation of a class (with no arguments) calls the default
constructor:
Rectangle r;
Constructor Syntax
class <Class_Name>
{
...
public:
<Class_Name>();
...
};
Constructors with Parameters
❖ To create a constructor that takes arguments:
❖ Indicate parameters in prototype:
Rectangle(double , double );
❖ Use parameters in the definition:
Rectangle::Rectangle(double w, double h)
{
width = w;
height = h;
}
❖ You can pass arguments to the constructor when you create an object:
Rectangle r2(6, 4);
More About Default Constructors
❖ If all of a constructor's parameters have default arguments, then it is a default
constructor. For example:
Rectangle r;
26
Overloading Constructors
❖ A class can have more than one constructor. They can be overloaded.
❖ The compiler automatically call the one whose parameters match the
arguments.
Rectangle();
Rectangle(double);
Rectangle(double, double);
27
Destructor
❖ Destructor: responsible for the necessary cleanup of a class when lifetime of
an object ends.
❖ Destructors cannot:
❖ return a value
❖ accept parameters
❖ Destructors must have the same name as the class.
❖ Only one destructor per class, i.e., it cannot be overloaded
❖ If constructor allocates dynamic memory, destructor should release it
28
Destructor Syntax
class <Class_Name>
{
...
public:
~<Class_Name>();
...
};
Using Private Member Functions
❖ A private member function can only be called by another member function
❖ It is used for internal processing by the class, not for use outside of the class
❖ If you wrote a class that had a public sort function and needed a function to
swap two elements, you’d make that private
30
Arrays of Objects
❖ Objects can be the elements of an array:
Rectangle rooms[8];
31
Arrays of Objects
❖ Must use initializer list to invoke constructor that takes arguments:
Rectangle rectArray[3]={Rectangle(2.1,3.2),
Rectangle(4.1, 9.9),
Rectangle(11.2, 31.4)};
32
Accessing Objects in an Array
❖ Objects in an array are referenced using subscripts
rectArray[1].setWidth(11.3);
cout << rectrArray[1].getArea();
Pointer to Class
❖ Objects can also be pointed by pointers. Class is a valid type.
❖ Class pointers is similar to struct pointers.
❖ E.g.:
34
Using the this Pointer
❖ Every object has access to its own address through a pointer called this (a
C++ keyword)
35
Summarise
❖ Understand Class: concept and definition, encapsulation
❖ Member functions, static and const members
❖ Constructor/Destructor and overloaded operators
36
Hochiminh City University of Technology
Computer Science and Engineering
[CO1027] - Fundamentals of C++ Programming
Inheritance Credits: 3
Outline
❖ Operator overloading
❖ Friendship
❖ Inheritance
2
Operator overloading
Fundamentals of Operator Overloading
• Overloading an operator
–Write function definition as normal
–Function name is keyword operator followed by the symbol for the operator being
overloaded
–operator+ used to overload the addition operator (+)
• Using operators
–To use an operator on a class object it must be overloaded unless the assignment
operator(=)or the address operator(&)
•Assignment operator by default performs memberwise assignment
•Address operator (&) by default returns the address of an object
4
Restrictions on Operator Overloading
Operators that can be overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]
5
Restrictions on Operator Overloading
• Overloading restrictions
–Precedence of an operator cannot be changed
–Associativity of an operator cannot be changed
–Arity (number of operands) cannot be changed
• Unary operators remain unary, and binary operators remain binary
• Operators &, *, + and - each have unary and binary versions
• Unary and binary versions can be overloaded separately
• No new operators can be created
–Use only existing operators
• No overloading operators for built-in types
–Cannot change how two integers are added
–Produces a syntax error
Friendship
Friendship
❖ Friends are functions or classes declared with the friend keyword.
❖ Using friend functions can enhance performance.
8
Friend function member
❖ A non-member function can access private and protected members of class if
it is declared as a friend of class.
❖ E.g.:
class Student {
❖ . . .
public:
friend Student duplicateStudent(Student& a);
};
9
Friend class
❖ Friend class: is a class whose members can access to private and protected
members of other classes.
❖ class Lecturer;
class Student {
friend class Lecturer;// lecturer is a friend
. . .
};
10
Inheritance
What Is Inheritance?
❖ Provides a way to create a new class from an existing class
❖ The new class is a specialized version of the existing class
Advantages of inheritance
❖ When a class inherits from another class, there are three benefits:
❖ You can reuse the methods and data of the existing class
❖ You can extend the existing class by adding new data and new methods
❖ You can modify the existing class by overloading its methods with your
own implementations
The "is a" Relationship
❖ Inheritance establishes an "is a" relationship between classes.
❖ A poodle is a dog
❖ A car is a vehicle
❖ A flower is a plant
❖ A football player is an athlete
Inheritance – Terminology and Notation in C++
• Base class (or parent) – inherited from
• Derived class (or child) – inherits from the base class
• Notation:
class Student // base class
{
. . .
};
class UnderGrad : public student
{ // derived class
. . .
};
Inheritance Exmaple
Triangle
Square
Rectangle
Shape Polygon
Parallelogram Rhombus
Ellipse Circle
16
Inheritance Syntax
❖ class <CName> [: <access specifier> <BaseCName>] {
. . .
};
❖ E.g.:
class Polygon : public Shape { . . . };
class Rectangle : public Polygon { . . . };
class Square : public Rectangle, public Rhombus { . . . };
class Ellipse: public Shape { . . . };
17
Inheritance Example
#include "Shape.h“
class Polygon : public Shape {
int nVertex;
Vector2D* pVertex;
public:
Polygon(int n) : Shape(), nVertex(n) {}
class Shape {
~Polygon();
int id;
void draw();
public: };
Shape() { id = 0; }
~Shape();
void draw(); #include "Shape.h“
}; class Ellipse : public Shape {
float theta;
Vector2D center, len;
public:
Ellipse();
~Ellipse();
void draw();
};
18
Back to the ‘is a’ Relationship
• An object of a derived class 'is a(n)' object of the base
class
• Example:
- an UnderGrad is a Student
- a Mammal is an Animal
• A derived object has all of the characteristics of the base
class
What Does a Child Have?
An object of the derived class has:
• all members defined in child class
• all members declared in parent class
24
Inheritance vs. Access
How inherited base class members
appear in derived class
Base class members
private: x private x is inaccessible
protected: y base class
private: y
public: z private: z
27