Procedure Oriented Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

Procedure oriented programming

A procedural language is a type of computer programming language that specifies a series


of well-structured steps and procedures within its programming context to compose
a program. It contains a systematic order of statements, functions and commands to
complete a computational task or program.

 In the procedure oriented approach, the problem is viewed as the sequence of things
to be done such as reading, calculating and printing.

 The technique of hierarchical decomposition has been used to specify the tasks to be
completed for solving a problem.

 It means “a set of procedures” which is a “set of subroutines” or a “set of functions“.

 For example, a program may involve collecting data from user (reading), performing
some kind of calculations on the collected data (calculation), and finally displaying
the result to the user when requested (printing).

 All the 3 tasks of reading, calculating and printing can be written in a program with
the help of 3 different functions which performs these 3 different tasks.

 Some Characteristics exhibited by procedure-oriented programming are:

 Large programs are divided into smaller programs known as functions.

 Most of the functions share global data.

 Data move openly around the system from function to function.

 Functions transform data from one form to another.


 Employs top-down approach in program design.

Object Oriented Paradigm


 OOP treats data as a critical element in the program development and does not allow
it to flow freely around the system.

 It ties data more closely to the function that operate on it, and protects it from
accidental modification from outside function.

 OOP allows decomposition of a problem into a number of entities called objects and
then builds data and function around these objects.

 It is a certain through which software can be developed.

 The goals of this methodology are to achieve Software Systems that are reliable,
reusable, extensible; hence, more useful in the long run.

 The methodology achieves its goals by the help of a collection of objects that
communicate by exchanging messages.

 Some of the features of object oriented programming are:

 Emphasis is on data rather than procedure.

 Programs are divided into what are known as objects.

 Data is hidden and cannot be accessed by external function.


 Objects may communicate with each other through function.

 New data and functions can be easily added whenever necessary.

 Follows bottom up approach in program design.

Basic Concepts of Object Oriented Programming


 Objects

 Classes

 Data abstraction and encapsulation

 Inheritance

 Polymorphism

 Dynamic binding

 Message passing

Objects

 Objects are the basic run time entities in an object-oriented system.

 They may represent a person, a place, a bank account, a table of data or any item that
the program has to handle.

 Programming problem is analyzed in term of objects and the nature of communication


between them.

 Program objects should be chosen such that they match closely with the real-world
objects.
Classes

 The entire set of data and code of an object can be made a user-defined data type with
the help of class.

 objects are variables of the type class.

 Once a class has been defined, we can create any number of objects belonging to that
class.

 For examples, Mango, Apple and orange members of class fruit.

 If fruit has been defines as a class, then the statement

Fruit Mango;

Will create an object mango belonging to the class fruit.

 Class refers to a blue print.it defines the variables and methods the object support.it is
the basic unit of encapsulation.it also defines as a collection of a similar types of
objects.
Encapsulation

 The wrapping up of data and function into a single unit (called class) is known as
encapsulation.

 The data is not accessible to the outside world, and only those functions which are
wrapped in the class can access it.

 The encapsulation is the inclusion-within a program object-of all the resources needed
for the object to function, basically, the methods and the data.

 In OOP the encapsulation is mainly achieved by creating classes, the classes expose
public methods and properties.

 A class is kind of a container or capsule or a cell, which encapsulate a set of methods,


attribute and properties to provide its indented functionalities to other classes. In that
sense, encapsulation also allows a class to change its internal implementation without
hurting the overall functioning of the system.

Class: student

Attributes: st_name, st_id,


branch, semester

Functions: Enroll()
Displayinfo()
Data Abstraction

 Abstraction refers to the act of representing essential features without including the
background details or explanation.

 Abstraction is an emphasis on the idea, qualities and properties rather than the
particulars (a suppression of detail). The importance of abstraction is derived from its
ability to hide irrelevant details and from the use of names to reference objects.

 Abstraction is essential in the construction of programs. It places the emphasis on


what an object is or does rather than how it is represented or how it works. Thus, it is
the primary means of managing complexity in large programs.

 While abstraction reduces complexity by hiding irrelevant detail

Inheritance

 Inheritance is the process by which objects of one class acquired the properties of
objects of another classes.

 It supports the concept of hierarchical classification.

 “Inheritance is the mechanism to provides the power of reusability and extendibility.”

 “Inheritance is the process by which one object can acquire the properties of another
object.”

Point

Line
Polymorphism

 Polymorphism means that the same thing can exist in two forms.

 “Polymorphism is in short the ability to call different functions by just using one type
of function call.”

Dynamic Binding

 Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time.
 The draw procedure will be redefined in each class that defines the object.

 At run-time, the code matching the object under current reference will be called.

Message Passing

 Creating classes that define object and their behavior,

 Creating objects from class definitions,

 Establishing communication among objects. FacultyObject

Performance

MgmtObject Performance
Result

Applications and Benefits of using OOP

 User interface design such as windows, menu…

 Real time systems

 Simulation and modelling

 Object oriented databases

 AI and expert systems

 Neural networks and parallel programming


 Decision support and office automation system

Benefits of OOP

 It is easy to model a real time system as real objects are represented by programming
objects in oop. The objects are processed by their member data and functions.it is easy
to analyse the user requirements.

 With the help of inheritance we can reuse the existing class to derive a new class such
that the redundant code is eliminated and the use of existing class is extended.

 In OOP data can be made a private to class such that only member functions of the
class can access the data. This principle of data hiding helps the programmer to build
a secure program that cannot be invaded by code in other part of the program.

 With the help of polymorphism the same function or same operator can be used for
different purposes. This helps to manage software complexity easily.

 Large problems can be reduced to smaller and more manageable problems. It is easy
to partition the work in a project based on objects.

 It is possible to have multiple instances of an object to co-exist without any


interference i.e., each object has its own separate member data and function.

Simple C++ Program


#include<iostream>

Using namespace std;

int main()

cout<<“c++ is better than c \n”;

return 0;

Comments

 C++ introduces a new comment symbol // (double slash).

// This is an example of

// C++ program to illustrate

// some of its features

The C comment symbols /*,*/


/* This is an example of C++ program to illustrate some of its features */

Program Features

Output operator

Cout<<”C++ is better than C.”;

The iostream File

#include <iostream>

Namespace

Using namespace std;

Input Operator

cin >> number1;

Return Type of main()

 In C++, main () returns an integer value to the operating system.

 Therefore, every main () in C++ should end with a return (0) statement; otherwise a
warning an error might occur.

 Since main () returns an integer type for main () is explicitly specified as int.

 We have used the insertion operator << repeatedly Cascading of I/O Operators

 in the last two statements for printing results.

 The statement

Cout << “Sum = “ << sum << “\n”;

Example
#include // include header file

using namespace std;

class person

{ char name[30];

Int age;

public:

void getdata(void);
void display(void);

};

void person :: getdata(void)

{ cout <<“Enter name: “;

cin >> name;

cout<< “Enter age: “;

cin >> age;

Void person : : display(void)

{ cout <<“\nNameame: “ << name;

cout << “\nAge: “ << age;

Int main()

{ person p;

p.getdata();

p.display();

Return 0;

} //end of example

The output of program is:

Enter Name: Ravinder

Enter age:30

Name:Ravinder

Age: 30

Name Space Scope

 Named entities, such as variables, functions, and compound types need to be declared
before being used in C++.

 The point in the program where this declaration happens influences its visibility:
An entity declared outside any block has global scope, meaning that its name is valid
anywhere in the code.

While an entity declared within a block, such as a function or a selective statement, has block
scope, and is only visible within the specific block in which it is declared, but not outside it.

Variables with block scope are known as local variables.

For example, a variable declared in the body of a function is a local variable that extends
until the end of the the function (i.e., until the brace } that closes the function definition), but
not outside it:

The visibility of an entity with block scope extends until the end of the block, including inner
blocks. Nevertheless, an inner block, because it is a different block, can re-utilize a name
existing in an outer scope to refer to a different entity; in this case, the name will refer to a
different entity only within the inner block, hiding the entity it names outside. While outside
it, it will still refer to the original entity. For example:

Example of namespace

// inner block scopes

#include <iostream>

using namespace std;

int main ()

int x = 10;

int y = 20;

int x;

// ok, inner scope. x = 50;

// sets value to inner x y = 50;

// sets value to (outer) y

cout << "inner block:\n";

cout << "x: " << x << '\n';

cout << "y: " << y << '\n';

}
cout << "outer block:\n";

cout << "x: " << x << '\n';

cout << "y: " << y << '\n';

return 0;

Structure of C++ Program

Creating the Source File

 Like C programs can be created using any text editor.

 For example, on the UNIX, we can use vi or ed text editor for creating using any text
editor for creating and editing the source code.

Compiling and Linking

 For compiling

g++ example.cpp

c++ example.c++

 For linking

c++ file1. -o file2


TOKENS

 Tokens are the basic building blocks in C++ language. The smallest individual units
in a program are known as tokens.

 A program is constructed using a combination of these tokens.

FIVE TYPE OF TOKENS


Keywords
Variables

Constants

Strings

Operators
KEY WORDS

Definition:

Sequence of characters that have a fixed meaning.

 Keywords must be written in lower case.

 Reserved identifiers and can’t be used as names for the

 program variables
 user-defined program elements

Examples:

 int, float, char, double, switch, break, char, const, Continue, default, for, if, goto,
static, void, sizeof, while, return, int, long, do, while etc…

VARIABLES

Definition:

A variable is a quantity whose value may change during the program execution.

Examples:

int a, char choice, etc.,


Variables in
C++

Numeric Character
Variables Variables

Alphabets and
To store either integer
numbers from 0-9
values or floating
inserted between
point values
single quotes

 Naming Conventions:

A variable name should

• contain alphabets (a-z , A-Z) and digits (0-9).

• not start with a number or a digit.

• not be a keyword.

• case sensitive.

CONSTANTS

Definition: The quantities whose value do not change during the program execution are
known as constants.
STRINGS

Definition:

A group of characters that are treated as a single data item enclosed in double quotes are
known as strings.

General syntax:

• char string-name[size];

• size determines the number of characters in the string name.

Example: char city[9]=“New York”;

OPERATORS

Definition:

An operator is a symbol that performs

operations on one or more operants.

There are 8 types of operators supported by C++

language.

EIGHT TYPES OF OPERATORS

• Arithmetic operators (+,-,*,/,%)

• Relational operators (==,!=,<,>,<=,>=)

• Logical operators (||,&&,!)


• Conditional operators (? :)

• Assignment operators (=,+=,-=,/=,*=,%=,)

• Increment /decrement operators (++,--)

• Bitwise operators (&,|,^,<<,>>,~)

• Miscellaneous/special operators (sizeof,*,->)

DATA TYPES

 Data types are means to identify the type of data and associated operations of
handling it. C++ provides a predefined set of data types for handling the data it uses.
When variables are declared of a particular data type then the variable becomes the
place where the data is stored and data types is the type of value(data) stored by that
variable. Data can be of may types such as character, integer, real etc. since the data to
be dealt with are of may types, a programming language must provide different data
types.

 FUNDAMENTAL
DATA TYPES

DATA TYPE
DATA TYPES MODIFIERS

DERIVED DATA
TYPES

FUNDAMENTAL DATA TYPES


USER DEFINED
INTEGER DATA TYPE DATA TYPES
 Integers are whole numbers with a machine dependent range of values. A good
programming language as to support the programmer by giving a control on a range
of numbers and storage space. C has 3 classes of integer storage namely short int, int
and long int. All of these data types have signed and unsigned forms. A short int
requires half the space than normal integer values. Unsigned numbers are always
positive and consume all the bits for the magnitude of the number. The long and
unsigned integers are used to declare a longer range of values.

CHARACTER DATA TYPE


 It can store any member of the C++ implementation's basic character set. If a
character from this set is stored in a character variable, its value is equivalent to the
integer code of that character. Character data type is often called as integer data type
because the memory implementation of char data type is in terms of the number code.

FLOAT DATA TYPE

 A number having fractional part is a floating- point number. An identifier declared as


float becomes a floating-point variable and can hold floating-point numbers. floating
point variables represent real numbers. They have two advantages over integer data
types:-

1: they can represent values between integers.

2: they can represent a much greater range of values.

they have one disadvantage also, that is their operations are usually slower.

DOUBLE DATA TYPE

 The data type double is also used for handling floating-point numbers. But it is treated
as a distinct data type because, it occupies twice as much memory as type float, and
stores floating-point numbers with much larger range and precision. It is slower that
type float.

VOID DATA TYPE

 It specifies an empty set of values. It is used as the return type for functions that do
not return a value. No object of type void may be declared. It is used when program or
calculation does not require any value but the syntax needs it.

DERIVED DATA TYPES

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.

That means that, for example, we can store 5 values of type int in an array without
having to declare 5 different variables, each one with a different identifier. Instead of
that, using an array we can store 5 different values of the same type, int for example,
with a unique identifier.

 Like a regular variable, an array must be declared before it is used. A typical


declaration for an array in C++ is:
type name [elements];
NOTE: The elements field within brackets [ ] which represents the number of elements the
array is going to hold, must be a constant value, since arrays are blocks of non-dynamic
memory whose size must be determined before execution.

VALID OPERATIONS WITH ARRAYS:-

 billy[0] = a;

 billy[a] = 75;

 b = billy [a+2];

 billy[billy[a]] = billy[2] + 5;

PROGRAM:-

// arrays example

#include <iostream>

using namespace std;

int billy [] = {16, 2, 77, 40, 12071};

int n, result=0;

 OUTPUT:- 12206

 int main () {

 for ( n=0 ; n<5 ; n++ )

 {

 result += billy[n];

 }

 cout << result;

 return 0;

 }

FUNCTIONS:-

Function groups a number of program statements into a unit and gives it a name. This unit
can be invoked from other parts of a program. A computer program cannot handle all the
tasks by it self. Instead its requests other program like entities – called functions in C – to get
its tasks done. A function is a self contained block of statements that perform a coherent task
of same kind.
The name of the function is unique in a C Program and is Global. It means that a function can
be accessed from any location with in a C Program. We pass information to the function
called arguments specified when the function is called. And the function either returns some
value to the point it was called from or returns nothing.

We can divide a long C program into small blocks which can perform a certain task. A
function is a self contained block of statements that perform a coherent task of same kind.

We first declare the function and then at the end of the program we define the function.

POINTERS:-

 The memory of your computer can be imagined as a succession of memory cells, each
one of the minimal size that computers manage (one byte). These single-byte memory
cells are numbered in a consecutive way, so as, within any block of memory, every
cell has the same number as the previous one plus one.

This way, each cell can be easily located in the memory because it has a unique
address and all the memory cells follow a successive pattern. For example, if we are
looking for cell 1776 we know that it is going to be right between cells 1775 and
1777, exactly one thousand cells after 776 and exactly one thousand cells before cell
2776.

 The general form of declaring the pointer is

type*ptr;

REFERENCES:-

 It is an alternative name for an object. A reference variable provides an alias for a


previously defined variable. It’s declaration consists of a base type, an
&(ampersand), a reference variable name equated to a variable name.

 the general form of declaring is:-

type&ref-var = var-name;

CONSTANTS:-

 C++ constants are not very different from any C++ variable. They are defined in a
similar way and have the same data types and the same memory limitations. However,
there is one major difference - once a constant has been created and value assigned to
it then that value may not be changed.

 Defining Constants with C++

There are actually three ways of defining a constant in a C++ program:

A. by using the preprocessor


B. by using the const key word

C. by using enumerators - these will have a range of integer values

It's also worth noting that there are two types of constant: literal and symbolic.

the general form of declaring a variable is:-

const int upperage = 50;

USER DEFINED DERIVED DATA TYPES

CLASS

 Class: A class is a collection of variables and function under one reference name. it is
the way of separating and storing similar data together. Member functions are often
the means of accessing, modifying and operating the data members (i.e. variables). It
is one of the most important features of C++ since OOP is usually implemented
through the use of classes.

 Classes are generally declared using the keyword class, with the following format:

class class_name { access_specifier_1: member1;

access_specifier_2:

member2; ...

} object_names;

STRUCTURES:-

 A data structure is a group of data elements grouped together under one name. These
data elements, known as members, can have different types and different lengths.

 Data structures are declared in C++ using the following syntax:

struct structure_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} object_names;

 where structure_name is a name for the structure type, object_name can be a set of
valid identifiers for objects that have the type of this structure. Within braces { } there
is a list with the data members, each one is specified with a type and a valid identifier
as its name.
Structure is different from an array in the sense that an array represents an aggregate of
elements of same type whereas a structure represents an aggregate of elements of arbitrary
types..

UNION:-

 Unions allow one same portion of memory to be accessed as different data types,
since all of them are in fact the same location in memory. Its declaration and use is
similar to the one of structures but its functionality is totally different:

union union_name {

member_type1 member_name1;

member_type2 member_name2;

member_type3 member_name3;

} object_names;

 All the elements of the union declaration occupy the same physical space in memory.
Its size is the one of the greatest element of the declaration.

 all of them are referring to the same location in memory, the modification of one of
the elements will affect the value of all of them. We cannot store different values in
them independent of each other.

One of the uses a union may have is to unite an elementary type with an array or
structures of smaller elements.

 The exact alignment and order of the members of a union in memory is platform
dependant. Therefore be aware of possible portability issues with this type of use.

ENUMERATION:-

 It can be used to assign names to integer constants.

//Program to illustrate Enumerator

#include<iostream.h>

void main(void)

enum type{POOR,GOOD,EXCELLENT};//this is the syntax of enumerator


int var;

var=POOR;//this makes programs more understandable

cout<<var<<endl;

var=GOOD;

cout<<var<<endl;

var=EXCELLENT;

cout<<var;

//poor=0

good=1

excellent=2

Storage Classes
 auto – created each time the block in which they exist is entered.

 register – same as auto, but tells the compiler to make as fast as possible.

 static – created only once, even if it is a local variable.

 extern – global variable declared elsewhere.

Dynamic Initialization of variables


 In C we have to declare all the variables at the starting of any function or scope.
However in C++ we can declare variable anywhere in the scope before its first use.
There is no need to declare all the variables at the starting of the scope.

 Example:
int main()
{
int n,sum=0;
for (int i = 1 ; i<=10;i++)
{
cin>>n;
sum=sum+n;
}
float average = sum/10;
}

 The process of initializing variable at the time of its declaration at run time is known
as dynamic initialization of variable.
Thus in dynamic initialization of variable a variable is assigned value at run time at
the time of its declaration.

 Example:
int main()
{
int a;
cout << “Enter Value of a”;
cin >> a;
int cube = a * a * a;
}

 In above example variable cube is initialized at run time using expression a * a * a at


the time of its declaration

Reference Variables
 A reference variable is an alias, that is, another name for an already existing variable.
Once a reference is initialized with a variable, either the variable name or the
reference name may be used to refer to the variable.

C++ REFERENCES VS POINTERS :

 C++ References vs Pointers

 References are often confused with pointers but three major differences between
references and pointers are:

 You cannot have NULL references. You must always be able to assume that a
reference is connected to a legitimate piece of storage.

 Once a reference is initialized to an object, it cannot be changed to refer to another


object. Pointers can be pointed to another object at any time.

 A reference must be initialized when it is created. Pointers can be initialized at any


time.

Creating References in c++

 Think of a variable name as a label attached to the variable's location in memory. You
can then think of a reference as a second label attached to that memory location.
Therefore, you can access the contents of the variable through either the original
variable name or the reference. For example, suppose we have the following example:
 Int I = 17;

 We can declare reference variables for i as follows.

 Int &r = I;

 Read the & in these declarations as reference. Thus, read the first declaration as "r is
an integer reference initialized to i" and read the second declaration as "s is a double
reference initialized to d.". Following example makes use of references on int and
double:

 #include <iostream>

 using namespace std;

 int main ()

 {

 // declare simple variables

 int i; double d;

 // declare reference variables

 int& r = i;

 double& s = d;

 i = 5;

 cout << "Value of i : " << i << endl;

 cout << "Value of i reference : " << r << endl;

 d = 11.7;

 cout << "Value of d : " << d << endl;

 cout << "Value of d reference : " << s << endl;

 return 0; }

 When the above code is compiled together and executed, it produces the following
result:

Output of above program

Value of i : 5
Value of i reference : 5

Value of d : 11.7

Value of d reference : 11.7

Scope resolution operator


 Scope resolution operator(::) is used to define a function outside a class or when we
want to use a global variable but also has a local variable with same name.

#include <iostream>

using namespace std;

char c = 'a'; // global variable

int main()

char c = 'b'; //local variable

cout << "Local variable: " << c << "\n";

cout << "Global variable: " << ::c << "\n"; //using scope resolution operator

return 0; }

Output:

Local variable: b Global variable: a

Scope resolution operator in class


#include <iostream>

using namespace std;

class programming

public:

void output(); //function declaration

}; // function definition outside the class

void programming::output()

{
cout << "Function defined outside the class.\n";

int main()

programming x; x.output();

return 0;

Output of program:
Function defined outside the class

Memory Management Operator


 There are two types of memory management operators in C++:

 new

 delete

 These two memory management operators are used for allocating and freeing memory
blocks in efficient and convenient ways.

 New operator:

 The new operator in C++ is used for dynamic storage allocation. This operator can be
used to create object of any type.

 General syntax of new operator in C++:

 The general syntax of new operator in C++ is as follows:

 pointer variable = new datatype;

 In the above statement, new is a keyword and the pointer variable is a variable of type
datatype.

 For example:

 int *a=new int;

 In the above example, the new operator allocates sufficient memory to hold the object
of datatype int and returns a pointer to its starting point. The pointer variable a holds
the address of memory space allocated.
 Dynamic variables are never initialized by the compiler. Therefore, the programmer
should make it a practice to first assign them a value.

 The assignment can be made in either of the two ways:

1. int *a = new int;

2. *a = 20

delete operator:

The delete operator in C++ is used for releasing memory space when the object is no
longer needed. Once a new operator is used, it is efficient to use the corresponding delete
operator for release of memory.

General syntax of delete operator in C++:

The general syntax of delete operator in C++ is as follows:

delete pointer variable;

Example

1. #include <iostream>

2. using namespace std;

3. void main()

4. {

5. //Allocates using new operator memory space in memory for storing a integer
datatype

6. int *a= new int;

7. *a=100;

8. cout << " The Output is:a= " << *a;

9. //Memory Released using delete operator

10. delete a;

11.

12. }

Output

The output is : a= 100


 It is possible to access the value of variables pointed by the pointer variables using
pointer. This is performed by using the Dereference operator in C++ which has the
notation *.

 The general syntax of the Dereference operator is as follows:

 *pointer_variable

 In this example, pointer variable denotes the variable defined as pointer. The * placed
before the pointer_variable denotes the value pointed by the pointer_variable.

Output

UNIT II

Control Structures

Classes and Objects


Class
Making inline function

You might also like