Professional Documents
Culture Documents
CSC 212 Lecture Slides Module
CSC 212 Lecture Slides Module
CSC 212:
Computer Programming II
(Core, 3 Credit Units)
No cell phones
No random coming in and going out
No noise making
If you are sleepy, go home
If you want to read email or surf the Web,
please do it elsewhere
Course Content
History and Fundamentals of C++. C vs C++. Standard
Inputs/Outputs: Insertion and Extraction operators. Control
Structures. Array, Structure and Union. String and Pointer.
Object-Oriented Design Technique: Class and Object, Class
and Composition, Data Member and Member Functions,
Aggregation and Inheritance: Friendship, Polymorphism; Class
iterators
Start
Problem
definition
Working
Program
Introduction to Programming
Software Development Life Cycle (SDLC):
1. Requirement analysis and specification
2. Design of the software
3. Implementation
4. Testing
5. Maintenance
6. Retirment/Obsolence
Fundamentals of C++
What is C++?
C++ is a general-purpose and high level programming language
It has imperative, object-oriented and generic programming features.
It runs on lots of platforms such as Windows, Linux, Unix, and Mac
It was created, designed & developed by Bjarne Stroustrup, a Danish
Computer Scientist at Bell Telephone Laboratories (now known as Nokia
Bell Labs) in Murray Hill, New Jersey.
He wanted a flexible and dynamic language as C with all its features, but
with additionality of active type checking, basic inheritance, default
functioning argument, classes, inlining, etc. and hence C with Classes (C+
+) was launched.
Fundamentals of C++
What is C++?
Top Programming Languages
Python
Java
C++
JavaScript
C#
IEEE Spectrum
Fundamentals of C++
C++ is good for developing:
High performance application
Video Games
Device drivers
Web browsers
Servers
Operating Systems
Constant:
A constant is a program entity whose value cannot be changed during the
execution of a program
Just like variables, they are equally associated with the four attributes as for
variable
Fundamentals of C++
Keywords:
They are words which have predefined meanings and can only be used for
the meaning for which they are defined.
C ++ Ke yw o rd s
Examples:
Valid identifiers: amount, total_sales, x, _sum, x1, abc123_c12
Invalid identifiers: amount sold, 9systems, auto, %change, 12
Good programming principle:
Always use descriptive names for your program entities. This will aid
the readability of programs. E.g.: use sales instead of s, total instead of
C++tis case sensitive. Thus, identifiers such as total,Total, and TOTAL are
3 different entities
Fundamentals
Comments:
of C++
They are explanatory text embedded in program codes to aid program
comprehension
They are non-executable and thus, ignored by the compiler
In C++, there are two types of comments:
Single line comment: this comment starts with double forward slashes
and runs to the end of the line in which it is placed. Example:
//this is a single line comment
Multiple line comment. This is also referred to as block comment and
it runs across multiple lines. It involves embedding text between /* and
*/. Example:
/* This is multiple
line comments in C++
*/
Fundamentals of C++
Data types:
Data types specify the kind of values a program entity can hold or process.
Two categories of data types: Basic and Derived
Basic data types: char, int, float, double, bool and void
Derived data types: array, structure, class
The following are the C++ Basic data types
operators can also be classified based on the number of operands they act
on: unary, binary and ternary operators
Types of expression – based on the operator used:
Arithmetic expressions
Relational expression
Logical expressions
Mixed expressions
Fundamentals of C++
Statement
A statement is a program entity which causes execution to occur.
In C/C++, statements are often expressions terminated with semicolons
There are different types of statements:
Declarative statements
Null statement
Simple statement
Compound (block) statement
Control statements
Fundamentals of C++
Declaration
Declaration is the specification of the data type and optionally the value of
an entity, usually variables and constants, in a program.
Before an entity can be used in C++, it must be declared or defined.
Variables and constants must be declared before usage.
The basic format for declaring a variable in C++ is:
data_type identifier;
E.g.: int age;
This declaration specifies that variable age is of type int. That is, age can
only hold whole numbers
Variables can be initialized with values during declaration using the
format: data_type identifier = initialValue;
E.g.: int age = 35;
Fundamentals of C++
Declaration (cont’d)
Variables of the same data type can be declared using a single type and the
variables separated with commas as follows
data_type identifier1, identifier2,…
identifierN;
E.g.: float x, y, z;
This declaration states that x, y and z are of the data type float.
Fundamentals of C++
Structure of C++ program:
A C++ program consist of one or more functions and classes, and one of
the functions must be called main where the execution of the program
commences.
All other functions, if any, must be called directly or indirectly from the
main function.
A typical C++ program is formatted as follow:
Header files
functions
main function
Example
#include <iostream>
int main( ) {
std::cout<<“Welcome to C++”;
}
Another format will be discussed later in the course
Fundamentals of C++
Header Files:
Header files are files that contain predefined functions which can be used to
develop programs
C++ compiler comes with several header files containing standard functions
defined to perform commonly used tasks in programming. Some instances of
header files are: iostream, fstream, new,and vector
C++ also contain header files from its predecessor, C. Some of these files are:
math.h, stdio.h, assert.h, float.h, and stdarg.h
To use any predefined function, the header file containing the function must be
added to the program by using the preprocessor directive #include
There two types of header file: Standard header files and Non-
standard header file.
Standard header files are the files provided by C++ and they are added using
the format: #include <filename.h>
Non-standard header files are the user-defined file and are added using the
format: #include “filename.h”
Fundamentals of C++
Namespace:
A namespace is a collection of names which gives unique definition to the
names within the collection i.e., no two names are the same within a
namespace.
C++ uses namespace to prevent name conflict especially in projects that are
lard and requires more than one programmer to write.
The most commonly used namespace is the standard namespace referred to as
std.
The using directive is used to specify namespace in programs. Example:
using namespace std;
The use of the directive prevents the repetitive is the the name of the
namespace to qualify any use of the name within the namespace in a program
Fundamentals
Standard Input/Output
of C++
C++ handles input and output as streams
The stream that feed the program with values is referred to as the input stream
The one that takes values from the program for outputting is referred to as the
output stream
The standard input and output are the keyboard and screen respectively
The standard input, keyboard, is associated with cin
The standard output, the screen, is associated with cout
To display values on the screen the insertion operator, << is used to specify the
value to the standard out using cout as follows:
cout<<x;
This will display the value stored in variable x on the screen
More variables/values can be displayed by using more insertion operators as
follows: cout<<x<<“ ”<<y<<“ ”<<z;
This will display the values of x, y and z with spaces inbetween them
Fundamentals of C++
Exercise:
Develop a C++ program that computes the root of quadratic equations
using the completing the square method. The program should handle
all possible type of solution of quadratic equations
Assignment 1
Develop a C++ program that computes the total payment for purchases
made by a customer given the following discount amount based on the
quantity the customer purchases:
Amount > 200000 < 1000000 => 3%
Amount>=1000000 => 7%
Fundamentals of C++
Standard Input/Output
Beside variables, expressions and literal can also be given as the operand for the
insertion operator as follows
cout<<“The value is: ”<< (a+b);
This output statement will display the value of the expression a+b, preceding it
with the string: “The Value is ”.
Assuming the values of a and b are 2 and 5 respectively, the output of the
statement will be:
The value is 7
Examples (cont’d)
if (descrinant > 0){
x1 = -b + sqrt(b*b – 4*a*c);
x2 = -b - sqrt(b*b – 4*a*c);
}
Control Structures in C++
Control Structure: Selection
The else clause:
This clause yields 2-alternative selection if statement with the following format:
if (expr) stmt1
else stmt2
where expr, stmt1 and stmt2 are as earlier defined.
The following steps are taken during the execution of the if..else statement:
1. expr is evaluated
2. If the value of expr is non-zero, stmt1 is executed otherwise (if the
value is zero) stmt2 is executed.
Control Structures in C++
Control Structure: Selection
The else clause
Example:
if (age < 40)
cout<<“The person is young”;
else
cout<<“The person is elderly”;
Control Structures in C++
Control Structure: Selection
The else if clause:
This clause provides feature for multiple conditional testing, and has the
following format:
if (expr_1) stmt_1
else if(expr_2) stmt_2
else if(expr_3) stmt_3
…
else stmt_N
During execution, the following steps are taken
1. expr1 is evaluated
2. If the value of expr1 is non-zero, stmt1 is executed otherwise (if the
value is zero) step 1 and 2 are repeated for the next expression until a non-
zero value is reach and associated stmt is executed.
Control Structures in C++
Control Structure: Selection
The else if clause:
Note that only one of the statements will be executed and that is the statement
associated with the expression that first returned a non-zero value
Example:
if (score >= 70) cout<<“Grade is A”;
else if(score >= 60) cout<<“Grade is B”;
else if(score >= 50) cout<<“Grade is C”;
else if(score >= 45) cout<<“Grade is D”;
else cout<<“Grade is F”;
Control Structures
Control Structure: Selection
in C++
The switch statement:
This statement is a simpler form of the if…else if statement and provides for
multiple condition testing as seen with the else if clause. The switch statement has
the following format:
switch (expr){
case value_1 : stmt_1
case value_2 : stmt_2
case value_3 : stmt_3
…
case value_N : stmt_N
[default : stmt_M ]
}
where expr is any expression that returns a value of bool, integer, char or enum
type
Control Structures
Control Structure: Selection
in C++
The switch statement:
This statement is a simpler form of the if…else if statement and provides for
multiple condition testing as seen with the else if clause. The switch statement has
the following format:
switch (expr){
case value_1 : stmt_1
case value_2 : stmt_2
case value_3 : stmt_3
…
case value_N : stmt_N
[default : stmt_M ]
}
where expr is any expression that returns a value of bool, integer, char or enum
type
Control Structures
Control Structure: Selection
in C++
The switch statement:
During execution, the expr is evaluated and execution begins with any case whose
value matches the expr until the end of the switch or the break statement is
encoutered
Example:
switch (grade){
case ‘A’ : gp = 5; break;
case ‘B’ : gp = 4; break;
case ‘C’ : gp = 3; break;
case ‘D’ : gp = 2; break;
case ‘F’ : gp = 0; break;
default : cout<<“Invalid grade”;
}
Control Structures in C++
Control Structure: Repetition
The while statement:
This is an iterative statement that repeatedly executive as long as a given condition
evaluates to a true or non-zero value. It has the following format:
while (expr) stmt
where expr can be Boolean, arithmetic, relational or logical expression, and
stmt can be any type of C++ statement.
Example 2:
for (int counter = 0; counter<100; counter++)
if(counter%2 == 0)
cout<<counter<<endl;
Control Structures in C++
Control Structure: Repetition
The break statement:
This statement causes exit from an iteration or a switch statement when it is
encountered. It has the following basic format:
break;
Example 1:
for (int i=1; i<100; i++){
if(i>55) break;
cout<<i<<“. Amos Bajeh”<<endl;
}
Control Structures in C++
Control Structure: Repetition
The continue statement:
This statement causes the current loop of an iteration to be skipped and iteration
continues with the next loop. Unlike the break statement which causes a
complete exit from an iteration, the continue statement does not cause a
complete exit but continues to the next iteration phase. It has the following basic
format:
continue;
Example 1:
for (int i=1; i<100; i++){
if(i==55) continue;
cout<<i<<“. Amos Bajeh”<<endl;
}
Control Structures in C++
Assignment 2
Modify the program written in Assignment 1 in such a way that the
program will allow its user to repeat the calculation for other
customers without rerunning it. (Hint: use iteration to repeat
computation).
Functions
Divide and Conquer
A complex or large problem can be solved by dividing it into smaller and
manageable subproblems. Solutions to these subproblems are systematically
merged to form the solution to the overall problem.
C/C++ provides the function for programming subproblems.
A function is a subprogram written to perform a specific task which is usually a
part of the overall task in a programming problem
There are two categories of functions in C/C++: Built-in functions and User-
defined functions.
A function is made to perform its designated task through function call or
invocation.
There are two categories of functions: Predefined (Built-in) Functions and
User-defined Functions.
Functions
Predefined (Built-in) Functions
These are the functions defined by C++ as a language for programmers to use for
rapid development of programs.
Commonly used/needed functions are defined in files usually called header files.
Programmers have access to these functions by using the include preprocessor
directive as follows: #include <heafer-file>
E.g.: #include <cmath>
This adds the cmath header file which contains some functions for performing mathematical operations
Some functions and their header file are specified in the table below:
User-defined Function
These are the functions defined by the programmer for performing specific
tasks.
C++ provides the ability for a programmer to defined functions in either header
files or within a program.
Functions
Function definition format.
return_type function_name (list_of_parameters){
//function body
}
The part in red is the function header which consist of the return type, the name of
the function and the list of parameters
return_type specifies the type of the data the function is expected to return
when called
function_name is the identifier with which the function can be
referenced/called.
list_of_parameters is the declaration of zero or more variables which
serve as input to the function. These variables/constants are referred to as formal
parameters. They are placeholders for the actual parameters that will be passed
into the function when it is called.
Functions
Function definition format.
return_type function_name (list_of_parameters){
//function body
}
The function body is a block of statement placed immediately after the function
header.
The return statement
A function is expected to return a value when it is invoked. Thus, C/C++ provides
the return statement for returning the value. It has the format:
return expr;
The return statement causes two actions to be taken:
1. Terminates the execution of the function, and
2. Returns a value to the point of the function call
Functions
Example 1: A function that determines the sum of two numbers. The numbers can
be passed into the function as its parameters
double addUp(double x, double y){
double sum = x + y;
return sum;
}
Or
double addUp(double x, double y){
return (x+y);
}
Functions
Example 2: A function that determines the maximum of two numbers. The numbers
can be passed into the function as its parameters
int determineMax(int a, int b){
int max = a;
if(max<b)max = b;
return max
}
Or int determineMax(int a, int b){
if(a>b) return a
else return b
}
Or int determineMax(int a, int b){
return (b>a)? b : a;
}
Functions
Function Call
For a function to perform it designated task and return a value, it must be invoked.
This is done by specifying the name and a list of actual parameters. The format
for function call/invocation is:
function_name(para_1, para_2, para_3, …);
para_1, para_2, para_3 are the actual values that will be assigned to the formal
parameters specified in the function definition.
Example3: The following are function calls for the addUp and determineMax
functions defined in example l and 2 above.
addUp(a, b);
determineMaximum(a, b);
Functions
Function Declaration
The definition of a function is expected before the function can be called.
C++ allows a function to be called before it is defined but a function declaration
will be needed before the call is made.
Function declaration is the function header terminated with a semicolon.
It specifies the return type, name of the function and the type(s) of the
parameters.
It has the following form:
return_type function_name(type1 p_1, type2 p_2,…);
p_1, p_2, … are optional.
Example: double addUp(double x, double y);
double addUp(double, double);
Functions
Function Declaration
#include <iostream>
using namespace std;
int main(){
double a = 35.9, b = 34.1;
cout<<"Values of a and b before the call"<<endl;
cout<<"a = "<<a<<"\tb = "<<b<<endl;
double x = sum(a, b);
cout<<"Values of a and b after the call"<<endl;
cout<<"a = "<<a<<"\tb = "<<b<<endl<<"Sum = "<<x;
return 0;
}
Functions
Types of Variables/Constants
Haven defined function, the following are the types of variables in C/C++
1. Local variables: variables/constants declared within a function. Such
variables have local scope which is the function
2. Global variables: variables/constant declared outside functions. Such
entities have global scope and are accessible from the point of declaration to
the end of the program. If within a function there is any variable/constant
that shares the same name with a global variable, the global variable will not
be accessible within the function.
3. Static variable: these are variables that retain their values within or outside
scope.
(Read more about them)
Static Variables Functions
#include <iostream>
using namespace std;
return z;
}
int main(){
cout<<"1. sum = "<<sum(5, 5)<<endl;
cout<<"2. sum = "<<sum(10, 10)<<endl;
cout<<"3. sum = "<<sum(20, 20)<<endl;
cout<<"4. sum = "<<sum(30, 30)<<endl;
cout<<"5. sum = "<<sum(40, 40)<<endl;
return 0;
}
Functions
Exercise:
1. Write a function that determines the number of days in February
given that only leap years have 29 days in February.
2. Write a program that contains a function that converts from 24-
hour notation to 12-hour notation. E.g.: 14:24 to 2:24PM.
Assignment 3
1. Write a C++ program that computes the area and perimeter of any
type of parallelogram of your choice. Define separate functions for
the computation of the area and perimeters.
2. Write a function that computes the standard deviation of four
scores. Write a program that calls the function.
Recursion
Functions
This is a feature in programming in which a function can involve itself. i.e., a
function is defined in terms of itself
Recursion is a form of iteration in which subsequent call to the function
involves calling to solve a subproblem of the overall problem
Thus, there are two paths in the definition of a recursive function:
The base case: this is the path that actually terminates the recursion.
The recursive case: this is the path that contains the call to the function passing a smaller
form of the problem which causes the recursion to move towards the base case the terminal
case.
int main(){
int n;
cout<<“Enter an integer”;
cin>>n;
cout<<n<<“! = "<<factorial(n)<<endl;
return 0;
}
Exercise: Write a recursive function that accept integer inputs and display them in the reverse
order of entry
Array
Array
This is a collection of items of the same kind.
It is a way of grouping variables of the same data type under one name.
Each item of the collection is referred to as an element
Each element of the array can be accessed using index which is the position
of the element within the array
The following format can be used to declare an array in C++:
data_type array_name[size];
E.g.: the following is a declaration of array of 10 integers
int scores[10];
C++ uses zero-indexing whereby the first element has index 0, the second
element has index 1, the third element has index 2, and so on. Thus, for the
above array, scores:
1st element is scores[0], 2nd element is scores[1], … 10th element is
scores[9]
Array
Array
Loops are good for stepping through array by using the index as the control
variable of the loop.
Example: Using loop to enter values into the array scores:
int scores[10];
for(int index=0; index<10; index++){
cout<<"Enter element"<<(index+1)<<": ";
cin>>scores[index];
}
Array in Memory
Array
In C++, an array is stored in contiguous memory.
The address of the first element is noted.
The location of other elements are computed by adding a number of bytes to
the address of the first element as depicted below:
0000
1002
1003 6
1004 233
1005 456
1006 4125
1007 45
1002
Array Initialization
Array
The elements of Array can be initialized with values during declaration
The initial values of the array are enclosed in curly braces.
The basic syntax for initializing array is:
data_type array_name[] = {val_1,val_2,val_3,…val_N};
There is no need to specify the array size.
C++ determines the size of array from the number of values enclosed in curly
braces
Example:
double a[] = {34.0, 15, 67.6, 77.9,
101.1};
Array and Function Array
The elements of Array can be passed into functions as parameters just like
ordinary variables
The data type of the array element must be the same or convertible to that of
the parameter
Also, the whole array can be passed to functions. The parameter declaration
can be specified as follows:
int func_name(int array_parameter[], int size){
}
There is no need to specify the array size. If specified, C++ ignores it. Thus,
an extra parameter is required to specify the size of the array.
The actual parameter in the function call is the name of the array. E.g.:
int a[5];
...
func_name(a, 5);
Array and Function Array
The name of array is a constant pointer to the first element of the array
Thus, passing array to function is a pass by reference.
This implies that any changes made to the array in the function will reflect
outside the function.
Thus, array can be used as a means of returning more than one value from a
function
Instances where array argument is not to be altered, it is safe to declare the
array parameter as constant by using the const keyword as follows:
double funct_name(const int a[], int size){
...
}
This prevents any intentional or accidental change to the array
Array
Searching Array
One of the task often performed on collections is searching through it for a
target component
This searching is to identify whether the element exist and its position within
the collection
There two approach to searching a collection: Linear Search and Binary
Search – linear search will be discussed
Linear search, as the name implies, is a search conducted from the first
element of the collection and proceeds serially through the collection until
either the element is found or the end of the collection is reached in which
case the target doesn’t exist in the collection
The following function conducts a linear search on the array parameter and
returns the index of the target or -1 if the target is not found in the array
Array
Searching Array