Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 81

Department of Computer Science

Faculty of Communication & Information Sciences


University of Ilorin, Ilorin, Nigeria

CSC 212:
Computer Programming II
(Core, 3 Credit Units)

Amos O. BAJEH, PhD


Room 29, Ground Floor/ Sub Dean’s Office
FCIS Building
Lecture Etiquette/Principles

 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

30h (T), 45h (P); C.


Algorithm Design & Analysis
 Week 1: Introduction to Programming
 Week 2: Fundamentals of C++
 Week 3: Control Structures
 Week 4: Functions
 Week 5: Continuous Assessment
 Week 6: Arrays and Vectors
 Week 7: Strings and Pointer
 Week 8: Structure and Union
 Week 9: OOP, Classes and objects
 Week 10: Templates

Introduction to
Computer Programming:
Programming
 Is the act of developing instructions for computers for problem solving.
 Problem-solving requires the designing of algorithms
 Algorithm is a series of ordered instructions which lead to a solution for
computational problems. A suitable analogy of algorithm is a recipe which
gives the ingredients and steps for preparing a delicacy
 Algorithm can be represented in two main forms: Flowchart and
Pseudocode
 Flowchart: this is a graphical representation of algorithms using symbols
some of which are:

 Pseudocode: this is an English-Like representation of algorithm that


involves the use of words such as Let, Input, print, etc.

Introduction to
Computer Programming:
Programming
 Example: An algorithm that determines how many times a name occurs in
a list of names
1. Get the list of names
2. Get the name to be checked
3. Set a counter to zero
4. Do the following for each name on the list: compare the name on the list
to the name to be checked. If the names are the same, then add 1 to the
counter
5. Output the number in the counter
Introduction to Programming
 Problem-solving phases:
 In order to develop a program to solve a problem, there are broadly two
phases to it: problem-solving phase and the implementation phase
 The Problem-solving phase entails the definition of the problem and
designing an algorithm to solve the defined problem
 The implementation phase entails the translation of the algorithm into a
program that the computer can process to solve the problem. A
programming language such as C++ is used to translate the algorithm into
a program.
Introduction to Programming
 Problem-solving phases:

Problem-solving Phase Implementation Phase

Start

Problem
definition

Algorithm design Translating to C+


+

Desk checking Testing

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

 Thus, it’s used by:


Fundamentals of C++
 C++ Development Environment:
 Text Editor: for entering of code
 C++ Compiler: for translating the code to machine executable form
 Linker: for linking programmer code to library code
OR
 Integrated Development Environment (IDE): is an integration of text
editor, compiler, linker, and debugger for program development. Examples
are;
MS Visual Studio (https://visualstudio.Microsoft.com/vs/community)
XCode for Mac from App Store
CLion (https://www.jetbrains.com/clion/download)
Code:Block (https://www.codeblocks.org/downloads/)
Fundamentals of C++
 C++ Development Environment:
 Text Editor: for entering of code
 C++ Compiler: for translating the code to machine executable form
 Linker: for linking programmer code to library code
OR
 Integrated Development Environment (IDE): is an integration of text
editor, compiler, linker, and debugger for program development. Examples
are;
MS Visual Studio (https://visualstudio.Microsoft.com/vs/community)
XCode for Mac from App Store
CLion (https://www.jetbrains.com/clion/download)
Code:Block (https://www.codeblocks.org/downloads/)
Fundamentals of C++
 C++ character set:
 C++ recognizes the following character:
 Alphabets: A – Z, a – z,
 Numbers: 0 – 9
 Special characters: +, -, /, ,, %, &, *, (, ), =, :, !, etc.
 Escape sequence:
Escape Sequence Description

\n Newline. Position the screen cursor to the


beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next
tab stop.
\r Carriage return. Position the screen cursor to the
beginning of the current line; do not advance to the
next line.
\a Alert. Sound the system bell.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double quote
character.
Fundamentals of C++
 Variable:
 A variable is a program entity whose value can change during the
execution of the program
 Variables are associated with four attributes:
 Name: this is identity by which the variable can be referenced
 Type: this specifies the kind of values that can be assigned to the variable
 Storage class: this determines the life span of the varibale
 Scope: this specifies the region within which the variable can be accessed

 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

Keywords common to the


C and C++ programming
languages
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
C++ only keywords
asm bool catch class const_cast
delete dynamic_cast explicit false friend
inline mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw true
try typeid typename using virtual
wchar_t
 Identifier:
Fundamentals of C++
 This is the name given to program entities (variables, named constants,
functions, classes, objects) by which they can be referenced
 The rules for assigning names to program entities are:
 Name can contain only alphabets, numbers and underscore (_)
 They must always start with an alphabet or underscore, and can be followed by more
alphabets, numbers and underscore
 There must be no space in an identifier
 It must not be any of the C++ keywords

 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

Data type Meaning Size (in byte)


char Character 1
int Integer 2 or 4
float Floating point 4
double Doubling floating point 8
bool Boolean 1
void modifiers: short,
 Type Empty/nothing 0
long, signed and unsigned
Fundamentals of C++
 Data types:
 The modifiers can be used with the int, double and char as shown below:
Data type Meaning Size (in byte)
signed int Same as int 4
unsigned int Can only store positive Integer 4
short Used for small integers ranging -32768 to 2
32767
unsigned short Used for small positive integers ranging 0 to 2
65,535
long Used for large integer; same as At least 4
long int
unsigned long Used for large positive integer; same as 4
unsigned long int
long double Used for large floating point numbers 12
unsigned char Used for characters ranging 0 to 255 1
Fundamentals of C++
 Literals:
 Literals are constants embedded within programs.
 The basic data types: char, int, float, double, and bool have literals

Data type Literal Example


char Character enclosed in single ‘A’
quotes
int Whole numbers 24
float Real numbers with fractions 4.345
double 123456.78534355
bool Boolean values, true and false true or false
String one or more characters “Amos Bajeh”
enclosed in double quotes “B”
Fundamentals of C++
 Expression
 An expression is a program entity which can be evaluated into a single
value. It is often formed from the combination of
variables/constants/functions with operators
 There are many operators in C++. Some basic operators are the
 Arithmetic operators: +, -, /, %
 Relational operators: ==, !=, <, >, <= and >=
 Logical operators: &&, ||, !
 Assignment operators: =, +=, -=, *=, %=, /=

 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

Reading Assignment: Read about the different forms in which the


standard I/O can be used for formatted output
Control Structures in C++
 Control Structure
They are statements that determine the order of execution of the statements in a
program
In structured programming, there classes of control structures are recognized
(Bohm and Jacopinni):
Sequence: the default order, starting from the top to the bottom
Selection: selects path of execution based on the truth or falsity ofgiven
condition
Repetition: repeats execution based on the truth or falsity of given condition
Besides, the sequence, C++ provide constructs for the other two classes of
control structures:
Selection: if and switch
Repetition: while, do…while, and for
Other control structures are the continue and break statement
Control Structures in C++
 Control Structure: Selection
The if statement
It is a single alternative selection statement with the following format:
if (expr) stmt
where expr can be arithmetic, relational, and/or logical expression, and
stmt can be any of the C++ type of statements.
During execution the following steps are taken:
1. expr is evaluated
2. If the value of expr is non-zero, stmt is executed otherwise (if the value
is zero) stmt is NOT executed but execution continues after the entire if
statement
 Example:
if (age<40) cout<<“The person is young”;
Control Structures in C++
 Control Structure: Selection
The if statement

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.

During execution, the following steps are taken


1. expr is evaluated
2. If the value of expr is true or non-zero, execute stmt and go to step 1.
otherwise terminate the iteration

Control Structures
Control Structure: Repetition
in C++
The while statement:
Example 1:
int counter = 0;
while (counter < 10) {
cout<<“Amos Bajeh”<<endl;
counter++;
}
Example 2:
int counter = 0;
while (counter <= 100){
if(counter%2 > 0)
cout<<counter<<endl;
counter++;
}
Control Structures in C++
 Control Structure: Repetition
The do…while statement:
This is similar to the while statement in that it repeatedly executive as long as a
given condition evaluates to a true or non-zero value. It is different in that it is a
post-test iteration i.e., the evaluation of the condition is done after each execution
(loop). Thus, do..while executes at leat one time and the while statement
executes at least zero time. The do…while statement has the following format:
do stmt while (expr)
where expr and stmt are as earlier defined.
During execution of this statement, the following steps are taken
1. stmt is executed
2. expr is evaluated
2. If the value of expr is true or non-zero, go to step 1. otherwise terminate the
iteration
All while statements can also be written using the do…while statement.

Control Structures
Control Structure: Repetition
in C++
The do…while statement:
Example 1:
int counter = 0;
do{
cout<<“Amos Bajeh”<<endl;
counter++;
} while (counter < 10);
Example 2:
int counter = 0;
do{
if(counter%2 > 0)
cout<<counter<<endl;
counter++;
} while (counter <= 100);
Control Structures in C++
 Control Structure: Repetition
The for statement:
This is the iterative statement that has the following format:
for (expr_1; expr_2; expr_3) stmt
where expr_1 and expr_3 are often arithmetic expressions for initializing and
incrementing/decrementing the control variable of the iteration. expr_2 is any
expression that yields a numeric or Boolean value. stmt is any C++ statement.
During execution of this statement, the following steps are taken
1. expr_1 is evaluated
2. expr_2 is evaluated
3. If expr_2 yields a non-zero/true value, stmt is executed, expr_3 is
evaluated, and step 1 is repeated. Otherwise, the iteration is terminated.
Note that expr_1 is evaluated only once and at the beginning of the iteration.
Control Structures in C++
 Control Structure: Repetition
The for statement:
Example 1:
for (int counter = 0; counter<100; counter++)
cout<<“Amos Bajeh”<<endl;

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:

Function Description Header file


int abs(int x) returns the absolute value of x cstdlib
double fabs(double y) returns the absolute value of y cmath
double sqrt(double z) returns the square root of z cmath
bool isdigit(char m) Returns true if m is a digit. cctype
Otherwise it returns false
Functions
Function Description Header file
double sin(x) Returns the Sine of x cmath
double cos(x) Returns the cosine of x cmath
double tan(x) Returns the Tangent of x cmath
strcmp(x, y) Returns -1, 0 or 1 if x is lexicographically less cstring
than, equal or greater than y respectively
strlen(x) Returns the number of characters in x cstring

 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

//without function declaration //with function declaration

#include <iostream> #include <iostream>


using namespace std; using namespace std;

int sum(int x, int y){ int sum(int, int);


return (x+y);
} int main(){
cout<<“Sum= “<<sum(5,6);
int main(){ return 0;
cout<<“Sum= “<<sum(5,6); }
return 0;
} int sum(int x, int y){
return (x+y);
}
Functions
 Parameter passing
In C++, parameters can be passed to functions in two ways: pass by value and pass
by reference.
Pass by value: in this method, the value(s) of the actual parameters are passed
(copied) into the formal parameters. This implies that any alteration made to the
formal parameters in the function do not alter the actual parameter variables.
The pass by value method is the default method when the definition and call
defined so far are used.
Pass by reference: this method involves the passing of the reference and not the
value of the actual parameters to the formal parameters. This method can be
implemented using alias or pointers. Using pointers will be discussed when
pointers are treated.
Using alias: this is done through the use of reference variables declared in the
function parameters.
Functions
Pass by reference using alias:

#include <iostream>
using namespace std;

double sum(double& x, double& y){


double sum = x+y;
x = 10;
y = 20;
return sum;
}

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;

double sum(double x, double y){


static double z =0;
z += x+y;

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.

Example: A typical exam to demonstrate recursion is the computation of the


factorial of integer.
n! = n * (n-1)!
(n-1)! = (n-1) * (n-2)!

1
 Recursion
Functions
#include <iostream>
using namespace std;

int factorial(int n){


if(n==1 || n==0)
return 1;
return n * factorial(n-1);
}

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

int linear_search(const int a[], int size, int target){


for(int i=0; i<size; i++)
if(a[i]== target)
return i;
return -1;
}
Array
 Sorting Array
 Another task often performed on collections is sorting the component in
either ascending or descending order
 There are several algorithms for sorting collections. One of the simple ones
is the Selection sort.
 Selection sort involves selecting the smallest element and position it at its
right position within the sorted array. It involves the following steps
1. Identify the smallest element and swap it with the element in the first
position
2. Identify the next smallest element and swap it with the element in the
second position.
3. Continue this until you get to the last but one element of the array.
The following functions implements the selection sort.
Array
 Selection sort
void sort(const int a[], int size){
int index_of_next_smallest;
for(int i=0; i<size-1; i++){
index_of_next_smallest =
determine_smallest(a, i+1, size);
int temp = a[i];
a[i] = a[index_of_next_smallest];
a[index_of_next_smallest] = temp;
}
}
Array
 Selection sort
int determine_smallest(const int a[], int start, int end){
int smallest = a[start];
int index_of_smallest = start;
for(int i=start+1; i<size; i++){
if(a[i]<smallest)
index_of_smallest = i;
}
return index_of_smallest;
}
Array
 Multidimensional Array
 The array discussed so far are classified as Linear Array
 Linear arrays are one-dimensional arrays which require only one index value
to access/reference the elements of the array
 Multidimensional Arrays have two or more dimensions and require moe than
one index to access any element of the array
 A typical multidimensional array is the two-dimensional array that can be
used to implement matrix
 The number of pair of square brackets in the declaration of array specifies
the number of diemsions of the array
 Thus, the following generally format can be used for array declaration
data_type array_name[size1][size2][size3]…[sizeN];
 Example: A two-dimensional array can be defined as follows:
int A[2][3];
Array
 Multidimensional Array
 The array declares a 2X3 matric
 Passing entire multidimensional array into function requires the specification
of the size of each dimension except the first.
 Example: A C++ function that computes the sum of two matrice:
void sum_of_matrice(const int A[][3], const int
B[][3], int C[][3], int
size1){
for(int i=0;i<size1;i++)
for(int j=0;j<2;j++)
c[i][j] = a[i][j]+b[i][j];
}

You might also like