Professional Documents
Culture Documents
Lecture Note by
Dr. Oyelami M. O.
Comparison of Some Programming Paradigms
Paradig
m
Main
characteristics
(examples)
Description
Computation
as statements that di
Imperativ
rectly
change
a
e
program state (data
fields)
Direct assignments,
common data
structures, global
variables
Examples
C, C++, Java,PH
P, Python
A style of imperative
C, C++, Java
Structograms, indentat
Structure programming with
ion,
d
more logical program
no goto statements
structure
Derived
from
structured
programming, based
Procedur
on
the
concept
al
of modular
programming or
the procedure call
Eventdriven inc
luding ti
me
driven
Program
flow is
ActionScript
determined
mainly
Main
loop,
event
by
events,
such
handlers, asynchronou
as mouse
clicks or
s processes
interrupts
including
timer
Treats datafields as
Objectoriented
Local
variables,
sequence,
selection, iteration,
and modularization
C, C++, Lisp,
PHP, Python
Objects,
C++, C#,Eiffel,
methods, message
objects manipulated passing, information
Java,PHP, Pytho
through
pre- hiding,
data n, Ruby, Scala
1
Paradig
m
Main
characteristics
(examples)
Description
Examples
Features
1.
2.
3.
4.
5.
6.
7.
of
Object
Oriented
Object
Class
Data Hiding and Encapsulation
Dynamic Binding
Message Passing
Inheritance
Polymorphism
2
Programming
Object
o Object is a collection of number of entities. Objects take up
space in the memory. Objects are instances of classes.
Class
o Class is a collection of objects of similar type. Objects are
variables of the type class.
Encapsulation
o Combining data and functions into a single unit
called class and the process is known as Encapsulation
Abstraction
o Hiding the complexity of program is called Abstraction and
only essential features are represented.
Dynamic Binding
o Refers to linking of function call with function definition is
called binding and when it takes place at run time called
dynamic binding.
Message Passing
o The process by which one object can interact with other
object is called message passing.
Inheritance
o it is the process by which object of one class acquires the
properties or features of objects of another class.
3
Polymorphism
o A greek term means ability to take more than one form. An
operation may exhibit different behaviours in different
instances. The behaviour depends upon the types of data
used in the operation.
Windows Programming
o Windows programming generally involves developing a GUIbased program.
o Many high-level languages are well suited for GUI
development by hiding much of the programming complexity
using object oriented techniques.
C++
C++ is a general purpose programming language.
It is a superset of the C programming language and created by
Bjarne Stroustrup
The key concept in C++ is class. A class is a user-defined type
Structure of a C++ Program
//my first program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
Comments
Initialization of Variables
Syntax: type identifier = initial_value;
Example: int a = 0;
// initialization of variables
#include <iostream>
using namespace std;
int main ()
{
int a=5; // initial value = 5
int b(2); // initial value = 2
8
int j;
j = i + 4;
}
j = i + 3;
}
Variables can also be declared in the for statement.
In that case the scope of the identifier is the loop :
int main()
{
int j;
j = 0;
for(int i = 0; i < 10; i++) j = j + i;
}
Basic Input/Output
The standard C++ library includes the header file iostream,
where the standard input and output stream objects are
declared.
Standard Output (cout)
By default, the standard output of a program is the screen,
and the C++ stream object defined to access it is cout.
cout is used in conjunction with the insertion operator,
which is written as << (two "less than" signs).
10
Strings
Variables that can store non-numerical values that are longer
than one single character are known as strings.
11
13
Boolean Literals
There are only two valid Boolean values: true and false.
These can be expressed in C++ as values of type bool by
using the Boolean literals true and false.
Declared Constants (const)
With the const prefix you can declare constants with a specific
type in the same way as you would do with a variable:
const int pathwidth = 100;
14
symbols
15
can
be
used
to
write
3.75.
16
Implicit Conversions
Basically operators are defined for two operands of the same
type. The compiler can automatically convert a numerical type
into another one so that the operator exists:
#include <iostream>
using namespace std;
int main()
{
cout << 3 + 4.3 << \n;
}
result is 7.3
The implicit conversion cannot be done to a type that loses
information (i.e. double to int for instance).
For example the % operators is only defined for integer
operands :
#include <iostream>
using namespace std;
int main()
{
cout << 3.0%4.0 << \n;
}
Boolean Operators
We can define more precisely what we called a condition in the
description of the if, for, and while syntax.
It is a boolean expression, which is an expression whose value
is of type bool.
17
#include <iostream>
using namespace std;
int main() {
bool c1, c2;
c1 = true;
c2 = !c1 && false;
cout << c1 << << c2 << \n;
}
The compiler is smart and will compute the value of the second
operand of a boolean operation only if this is necessary.
Comparison Operators
The comparison operators take two numerical operands and
have a Boolean value:
18
The equality and inequality are defined for any types and
return a Boolean value:
Assignment Operator
A strange thing in C++ is that assignments are also
expressions:
j = 3 + (i = 5);
is legal, and will assign to i the value 5, and to j the value 8.
But feel free not to use such weird tricks.
19
20
Precedence of Operators
The precedence of operators is the order used to evaluate
them during the evaluation of the complete expression.
To be compliant with the usual mathematical notations, the
evaluation is not left-to-right.
For example 3 + 4 * 5 + 6 * 7 is considered by the compiler as
3 + (4 * 5) + (6 * 7) and NOT AS (((3 + 4) * 5) + 6) * 7
When two operators have same precedence (i.e. when we have
the same operator twice), the evaluation is left-to-right
From greatest to lowest priority, the priority order is as
follows:
21
22
Control Structures
Control structures help a program to branch, repeat code or
take decisions instead of linear execution of instructions.
Conditional Statement
The if statement
The if statement executes a part of a program only if a given
condition is
if(condition)
<statement to execute if the condition is true>
or
23
if (condition)
<statement to execute if the condition is true>
else
<statement to execute if the condition is false>
A statement here is either a part of a program enclosed in { },
or a single line terminated with a ;.
For example :
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
if(n < 0) n = 0;
else {
n = 2 * n;
n = n - 1;
}
cout << n << \n;
system("pause");
}
Loops
Loops have as purpose to repeat a statement a certain number
of times or while a condition is fulfilled.
The for statement
The for statement repeats the execution of a part of a
program.
for(initialization; condition; increment)
<statement to repeat>
24
switch(k)
{
case 1:
cout << "one!\n";
break;
case 2:
cout << "two!\n";
break;
case 3:
cout << "three!\n";
break;
default:
cout << "Didnt get it, did you ?\n";
break;
system(pause);
}
}
Functions
Using functions we can structure our programs in a more
modular way, accessing all the potential that structured
programming can offer to us in C++.
A function is a group of statements that is executed when it is
called from some point of the program. The following is its
format:
type name ( parameter1, parameter2, ...)
{
Statements
}
where:
type is the data type specifier of the data returned by the
function.
name is the identifier by which it will be possible to call the
function.
28
return 0;
}
Passing Arguments by Reference
// passing parameters by reference
#include <iostream>
using namespace std;
void duplicate (int& a, int& b, int& c)
{
a*=2;
b*=2;
c*=2;
}
int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
}
Default Values in Parameters
}
int main ()
{
cout << divide (12);
cout << endl;
cout << divide (20,4);
system(pause);
return 0;
}
Overloaded Functions
Inline Functions
A recursive function calls itself and looks like what is shown below:
function( )
{
function( );
}
i.
Direct Recursion
ii.
Indirect Recursion
In direct recursion, a function a calls itself. That is, its code contains a call to
itself while in indirect recursion, the function a calls function b, b calls
another function c and so on until a is called again.
Of necessity, a good recursive function must have the following components:
i.
ii.
iii.
When the if statement becomes false, the current call then proceeds to
33
// factorial calculator
#include <iostream>
using namespace std;
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return (1);
}
int main ()
{
long number;
cout << "Please type a number: ";
cin >> number;
cout << number << "! = " << factorial (number);
return 0;
}
Function Prototype
To be able to call a function, it must have been declared in
some earlier point of the code.
Function prototyping allows you to do this.
// declaring functions prototypes
#include <iostream>
using namespace std;
void odd (int a);
void even (int a);
int main ()
{
int i;
do {
cout << "Type a number (0 to exit): ";
cin >> i;
odd (i);
} while (i!=0);
34
return 0;
}
void odd (int a)
{
if ((a%2)!=0) cout << "Number is odd.\n";
else even (a);
}
void even (int a)
{
if ((a%2)==0) cout << "Number is even.\n";
else odd (a);
}
Arrays
An array is a series of elements of the same type placed in
contiguous memory locations that can be individually
referenced by adding an index to a unique identifier.
For example, an array to contain 5 integer values of type int
called billy could be represented like this:
Example:
int billy [5] = { 16, 2, 77, 40, 12071 };
Accessing the Values of an Array
36
Multidimensional Array
Multidimensional arrays can be described as "arrays of
arrays".
For example, a bidimensional array can be imagined as a
bidimensional table made of elements, all of them of a same
uniform data type.
#include<iostream>
using namespace std;
#define WIDTH 2
#define HEIGHT 3
int jimmy [HEIGHT][WIDTH];
int n,m;
int main ()
{
for (n=0;n<HEIGHT;n++)
{
for (m=0;m<WIDTH;m++)
{
jimmy[n][m]=(n+1)*(m+1);
}
}
for (n=0;n<HEIGHT;n++)
for (m=0;m<WIDTH;m++)
{
cout<<jimmy[n][m]<<"\v";
}
system("pause");
return 0;
}
37
Arrays as Parameters
struct structure_name
{
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
38
.
.
} object_names;
struct product {
int weight;
float price;
};
product apple;
product banana, melon;
// structur.cpp -- a simple structure
#include <iostream>
#include <string>
using namespace std;
struct student // structure declaration
{
string name, sex;
short age;
};
int main()
{
student John;
cout << Enter Your Name \n;
cin>>John.name;
cout << Enter Your Sex \n;
cin>>John.sex;
cout << Enter Your Age \n;
cin>>John.age;
//output students particulars
cout << Your name is <<John.name<<\n;
cout << Your sex is <<John.sex<<\n;
39
An Overview of Pointers
Pointers are variables that store addresses of values.
Reference operator (&)
40
41
new
This returns
a block of memory large enough to hold
num_elements elements of the type type_name, with
pointer_name pointing to the first element.
Example
int* psome= new int[10];
psome points to the first element of the array. Alternatively, the
elements can be accessed as psome[0], psome[1], psome[9].
43
Listing 5
// structur.cpp -- a simple structure allocated using new
#include <iostream>
#include <string>
using namespace std;
struct student // structure declaration
{
string name, sex;
short age;
};
int main()
{
student* variable=new student;
cout << Enter Your Name \n;
cin>>variable->.name;
cout << Enter Your Sex \n;
cin>>variable->.sex;
cout << Enter Your Age \n;
cin>>(*variable).age;
//output students particulars
cout << Your name is <<variable->name<<\n;
cout << Your sex is <<variable->sex<<\n;
cout << Your age is <<variable->age<<\n;
system(pause);
return 0;
}
The other half is the delete operator, which lets you return
memory to the memory pool when you are finished with it. The
memory that you return or free can be reused by other parts of
your program.
You use delete by following it with a pointer to a block of
memory originally allocated with new:
int *ps=new int;
delete ps;
Note: You cannot use delete to free memory created by declaring
variables.
int jugs =5;
// ok
// allocate memory
delete pq;
Listing 6
#include<iostream.h>
#include<string.h>
char* getname (void);
// function prototype
int main(void)
{
char* name; // create a pointer to no storage
name=getname(); // assign address of string to name
cout<<name <<at <<(int*) name<<\n;
delete name; // memory freed
name=getname(); // reuse freed memory
47
mylong++;
mychar, would contain the value 1001.
myshort would contain the value 2002
mylong would contain 3004
Void Pointers
int main ()
{
char a = 'x';
int b = 1602;
increase (&a,sizeof(a));
increase (&b,sizeof(b));
cout << a << ", " << b << endl;
return 0;
}
Null Pointer
A null pointer is a regular pointer of any pointer type which has a special
value that indicates that it is not pointing to any valid reference or
memory address:
int * p;
p = 0; // p has a null pointer value
Other Data Types
1. Defined data types (typedef)
C++ allows the definition of our own types based on other
existing data types. We can do this using the keyword typedef,
whose format is:
3. Enumerations
enum enumeration_name
{
value1,
value2,
value3,
.
.
} object_names;
Example:
enum colors_t {black, blue, green, cyan, red, purple, yellow, white};
colors_t mycolor;
mycolor = blue;
Classes
A class is an expanded concept of a structure: instead of
holding only data, it can hold both data and functions.
An object is an instantiation of a class. In terms of variables, a
class would be the type, and an object would be the variable.
Classes are generally declared using the keyword class, with
the following format:
52
int * p;
p = 0; // p has a null pointer value
class class_name
{
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
class_name is a valid identifier for the class
object_names is an optional list of names for objects of this
class.
The body of the declaration can contain members, that can be
either data or function declarations, and optionally access
specifiers.
An access specifier is one of the following three keywords:
private, public or protected.
private members of a class are accessible only from within
other members of the same class or from their friends.
protected members are accessible from members of their same
class and from their friends, but also from members of their
derived classes.
public members are accessible from anywhere where the
object is visible.
By default, all members of a class declared with the class
keyword have private access for all its members.
Example
class CRectangle
{
int x, y;
53
public:
void set_values (int,int);
int area (void);
} rect;
You invoke a class member function, or method, by using a class object. You
do so by using the dot membership operator:
rect.set_values (3,4);
myarea = rect.area();
Here is the complete example of class CRectangle:
// classes example
#include <iostream>
using namespace std;
class CRectangle
{
int x, y;
public:
void set_values (int,int);
int area ()
{
return (x*y);
}
};
void CRectangle::set_values (int a, int b)
{
x = a;
y = b;
}
int main ()
{
CRectangle rect;
rect.set_values (3,4);
54
56