Académique Documents
Professionnel Documents
Culture Documents
C0mputer
Pr0gramming and
Numerical meth0ds
1
Basics of Procedure and
Object Oriented Pr0
2
Procedure Oriented Programming
In POP the main program is divided into a
number of functions.
3
Procedure Oriented Programming
• Pop consists of a list of instructions and
organizing them in to groups known as functions
4
Procedure Oriented Programming
• For eg., program may involve
5
Structure of POP
Main Program
Function - 4 Function - 5
6
Procedure Oriented Programming
In a multi-function program many
important data items are placed as
global.
7
Relationship of data and functions in
POP
8
Procedure Oriented Programming
Another drawback of POP is that it
does not model real world entities well.
9
Procedure Oriented Programming
• In large programs, it is difficult to identify
what data is used by which function
10
Characteristics of Procedure Oriented
Programming
• Emphasis is on doing things.
11
Characteristics of Procedure Oriented
Programming
• Data move openly around the system
from function to function
12
Object-Oriented Programming
13
Object-Oriented Programming
Data is hidden and cannot be
accessed by external functions.
14
OOP continue…
New data and functions can be added
whenever necessary.
15
Organization of data and functions in
OOP
Object A Object B
Data
Data
Functions
Data
Object C 16
Basic Concepts of OOP
Objects
Classes
Data Abstraction
Encapsulation
17
Basic Concepts of OOP
Inheritance
Polymorphism
Message passing
Dynamic binding
18
1.Objects
19
Objects continue…
An object is an instantiation of a class.
20
Representation of an object
Object: STUDENT
DATA
Student
Name Total
Date-of-birth
Marks
Average
FUNCTIONS
Total
Average Display
Display
21
2. Classes
A class is a collection of data and its
associated functions referenced under one
name.
23
3. Encapsulation
The wrapping up of data and its associated
functions into a single unit (class) is called
encapsulation.
26
Abstraction continue…
The attributes are sometimes called data
members because they hold information.
27
5. Inheritance
Inheritance is the process by which
objects of one class acquire the
properties of objects of another class.
28
Property inheritance
Birds
Attributes
Feathers
Lay eggs
Nonflying
Flying bird
bird
Attributes Attributes
................. ………………..
……………… ……………….
29
Inheritance continue…
Inheritance provides the idea of reusability.
30
Inheritance continue…
31
Inheritance continue…
32
Inheritance continue…
33
6. Polymorphism
Polymorphism means ability to take more than
one form.
Draw( )
35
7. Message passing
• Objects can communicate each other by
passing messages.
36
Message passing continue…
• Following are the basic steps in message
passing
38
Benefits/Advantages of OOP
Eliminates redundant codes - inheritance
• Client-server systems
41
Applications of OOP
• Hypertext, Hypermedia
• CIM/CAD/CAM systems
42
Introduction to C++
C++ is an OOP language.
It was developed by Bjarne Stroustrup
C++ is an extension of C
The important facilities that C++ adds to
C are
classes
inheritance
operator overloading
function overloading
43
C++ character set
• Alphabets – A-Z (uppercase letters)
a-z (lowercase letters)
• Numerals -0,1,2….9
• Special symbols - “ , }
,|,*,&,^,@,$,#,>,<,>=,<=,==,=,+,-,/ ,(, ),%,:, ;,{,}
&&,|| etc.
• White spaces
-back space (\b),horizontal tab (\t),
newline (\n)etc
44
Tokens
• Smallest individual units in a program.
• Tokens are:
keywords
identifiers
constants / literals
punctuators
operators
45
keywords
• Certain identifiers reserved for specific
usage in C++ are called keywords
• Declaring a class
• Declaring a function
• Declaring an object
48
Identifiers
A name used to identify a variable, a
function, a class or an object
49
Rules for naming identifiers
1 .Identifier is an arbitrary long sequence of letters and
digits.
50
Identifiers continue…
• Examples: num, add, rem , _avg,
addr2, FIELetc.
51
Constants/literals
Are tokens that represent data items that
never change their value during a program
run.
52
Integer constants
•Integer constants are the whole numbers.
53
Integer constants
• C++ allows three types of integer literals:
a) Decimal constant (Base 10)– a
sequence of digits with no zeros in the
beginning. eg . 123 , +56,-67….
b) Octal constants(Base 8)-Sequence of
digits starting with zero. Eg.
010,01237….
c) Hexadecimal constants(Base 16)-
sequence of digits preceded by OX or
Ox
ex . OX79 , 0xAB
54
Character constants
eg . „a „ , „y‟ , „L‟
55
Character constants
\b – backspace
\n – newline
\t-horizontal tab
\v – vertical tab
\a- alert
\f-form feed
\r- carriage return
56
Floating constants
Real numbers(numbers with fractional part)
1 .Fractional form
2. Exponential form
57
Floating constants
1 .Fractional form
• A floating constant in fractional form must
have at least 1 digit before the decimal point
and 1 digit after the decimal point.
58
Floating constants
2. Exponential form
• Ex . 12e -5
12.7E10
59
String literals
• Sequence of characters enclosed in double
quotes
60
Punctuators
• Punctuators are the symbols used in the
program as separators.
61
Punctuators
• Comma , ->used as a separator in a
function argument list.
62
Punctuators
• Equal to sign = -> used for variable
initialization, assignment operator in
expressions.
63
Variables
65
Variables
• Thus, the information represented by the variable
can change during the execution of the program
• Eg.
– int a,b,c; //a,b,c are integer variables
– char d;//d is a character type variable
66
Local Variables
• A local variable is a variable which is either a
variable declared within a function or is an
argument passed to a function.
67
Local Variables
• Eg. int main()
{
#include<iostream.h> int a,b;
void swap(int x, int y) cin>>a>>b;
cout<<“a=“<<a<<endl;
{ cout<<“b=“<<b<<endl;
int temp=x; swap(a,b);
x=y; cout<<“a=“<<a<<endl;
cout<<“b=“<<b<<endl;
y=temp; return 0;
} }
68
Global variables
• A global variable is a variable which is
accessible in multiple scopes.
69
Global variables
Eg.
int main()
#include<iostream.h>
{
double w;
void z() int i;
{ w=4;
w=0; return 0;
return; }
} • Here, w is a global
void q() variable, which has scope
{ in all the three functions
in this programs: z(), q()
int index; and main().
w=2;
• index and i are local
return; variables.
} 70
Dynamic initialization of variables:
• C++ allows initialization of the variables at run
time known as dynamic initialization.
• A variable can be declared and initialized at
run time using expressions at the place of
declaration.
eg, float area=3.14*r*r;
float average=sum/I;
71
C++ operators
• The tokens or symbols that performs some kind of
operations are called operators
• An operation requires an operator and operands
72
Arithmetic operators
Arithmetic operators may be :
73
Arithmetic operators
74
Arithmetic operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus(remainder of an
integer division)
75
Arithmetic operators
76
Assignment operators
77
Assignment operators
Operator Meaning
= Assignment
+= Assign the sum
-= Assign the difference
*- Assign the product
%= Assign the remainder
/= Assign the quotient
78
Assignment operators
Operator Meaning
>>= Assign right shift
<<= Assign left shift
&= Assign bitwise AND
!= Assign bitwise NOT
|= Assign bitwise OR
^= Assign bitwise XOR
79
Assignment operators
• Eg.
x+=y is equivalent to x=x+y
x-=y is equivalent to x=x-y
80
Comparison and logical operators
• Relational operators
• Equality operators
• Logical operators
81
Relational operators
83
Equality operator
84
Equality operator
Eg. Let a=6, b=8,c=9
a==b -> False
(a*b)!=c -> True
85
Logical operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
86
Logical operators
• Logical AND: The expression is true only if both
the conditions are true. General form is,
expression1 && expression2
Expression Result
True && True True
True && False False
False && True False
False && False False
87
Logical operators
• Logical AND Example:
Let a=2, b=3, c=5
88
Logical operators
• Logical OR: The expression is true if any one of
the conditions is true. General form is,
expression1 || expression2
Expression Result
0 || 0 0
0 || 1 1
1 || 0 1
1 || 1 1
89
Logical operators
• Logical OR example,
Let a=2, b=3, c=5
(a<b) || (b>c)
(2<3) || (3>5)
True || False -> True
90
Logical operators
• Logical negation: Logical expression can be
changed from false to true or from true to
false using the negation operator(!)
• General form;
!expression
Expression Result
!(true) False
!(false) True
91
Bitwise operators
• Bitwise complement:- This operator switches all the
bits in a binary pattern, ie, all the 0‟ s becomes 1‟s
and 1‟s becomes 0‟s.
92
Bitwise operators
• Left shift: The << operator is used for left
shifting.
For eg, Let x=33, its binary pattern is
00100001(8 bits)
x<<3 00100001(initial)
0 01000010
0 10000100
1 00001000(resultant)
93
Bitwise operators
• Right shift: The >> operator is used for right
shifting.
• For eg, Let y = 41, its binary pattern is
00101001
y>>2(initial) 00101001
00010100 1
(Resultant) 00001010 0
94
Bitwise operators
• Bitwise AND: The bitwise AND operations are
carried out between the two bit patterns of
the two operands.
Let, x=6 0110
y=3 0011
x&y 0010
95
Bitwise operators
• Bitwise OR: The bitwise OR operations are
similar to the bitwise AND and the result is 1 if
any one of the bit value is 1.
• The symbol | represents the bitwise OR
x=6 0110
y=1 0001
x|y 0111
96
Bitwise operators
• Bitwise Exclusive OR: This operation can be
carried out by the notation ^ .
• To generate a 1 bit in the result, a bitwise
exclusive OR needs a 1 in either number, but
not in both.
• Let, x=5 0101
y=2 0010
x^y 0111
97
Special operators:Unary operators
• Unary operators precedes their single operand.
• Unary minus (-) – to change the sign of a value
x=-50
• Unary Plus(+) – to represent a positive number
y=+55
• Increment (++)and decrement operators(--)
++ adds one to its operand
eg. x++ -> x=x+1
++x ->x=x+1
-- subtract one from its operand
eg. x-- -> x=x-1
--x ->x=x-1
98
Special operators:Unary operators
99
Special operators : conditional
operators
• Conditional operator(ternary operator) is
indicated by the symbol ?:
• This operator uses three expressions.
• The general form is,
expression1 ? Expression2 : expression3
• If expression 1 is true, then expression2 is
evaluated; otherwise expression3 is
evaluated.
100
Special operators : conditional
operators
• Eg, Let x=10;
y=x>9 ? 100 : 200;
• Y is assigned the value 100 if x>y .
• Otherwise ,y=200
101
Special operators :typecast
operator
• Converts a declared data type to some other
required type
• C++ provides a specific way for converting one
data type to other using typecast operator.
• Syntax:
(type-name)expression
Eg, avg=sum/(float)i;
102
Special operators :typecast
operator
• Type name behaves as if it is a function for
converting values to a designed type
– Eg, result=(int)(19.2/4);
– The cast operation(int) casts not only the 19.2 but
also the entire expression.
– The result is 4, rather than 4.8
103
Special operators :comma
operator
• C++ uses comma in two ways
• The first use of comma is as a
separator in the variable declaration.
– Eg, int a,b,c;
• used as a separator in a function
argument list
104
Special operators :scope
resolution operator
• C++ supports a mechanism to access a global
variable from a function in which a local
variable is defined with the same name as that
of the global variable.
• It is achieved using the scope resolution
operator.
• Syntax:
::variable name
The variable name is the global variable.
105
Special operators :scope
resolution operator
• The global variable to be accessed must be preceded by the
scope resolution operator.
• It directs the compiler to access a global variable, instead of
the one defined as local variable.
• Eg,
……
…….
{ Block 2
int x=10;
……..
{
int x=1; Block1
……..
}
……
}
106
Special operators :scope
resolution operator
• Block2 is contained in block1
• A declaration in an inner block hides a
declaration of the same variable in an outer
block
• Within the inner block, the variable x will refer
to the data object declared therein.
• ::x is used to access the global variable.
107
Memory management operators:
new and delete
• They are also called free store operators.
108
Memory management operators:
new and delete
• The new operator can be used to create objects of
any type.
• Syntax:
pointer-variable = new data-type;
• Pointer variable is a pointer of type data-type
• The new operator allocates sufficient memory to
hold a data object of type data-type and returns the
address of the object.
• The data-type may be any valid data type.
• The pointer variable holds the address of the
memory space allocated.
• Eg, p=new int; Where p is a pointer of type int. 109
Memory management operators:
new and delete
• We can initialize the memory using the new operator.
pointer-variable=new data-type(value);
Eg, int *p=new int(25);
111
Manipulators
• Manipulators are operators that are used to
format the data display.
• The most commonly used manipulators are
endl and setw.
• Endl:
– The endl manipulator when used in an output
statement, causes a linefeed to be inserted.
– Eg, cout<<“m”<<m<<endl;
cout<<“n”<<n<<endl;
112
Manipulators
• Setw:
– It is used to specify a common field width for all
the numbers and force them to be printed right
justified.
– Eg, cout<<setw(5)<<sum<<endl;
113
Increment and decrement operators
114
Increment and decrement operators
• Syntax:-
Increment operator:
++variable name or variable name++
Decrement operator:
--variable name or variable name--
• Example:
Increment operator: ++i, i++
Decrement operator:--i, i--
115
Increment and decrement
operators:Example programs
• Increment operator • Decrement operator
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int i=1; int i=20;
while(i<10) while(i>10)
{ {
cout<<i; cout<<i;
i++; i--;
} }
} }
116
Pre-increment and post increment
117
Pre-increment and post increment
118
Datatypes
C++ data types are:
• Built-in type
– Integral type– int & char
– Void
– Floating type – float & double
– Boolean
• Derived type
– Array
– Function
– pointer
– Reference
• User-defined type
– Structure
– Union
– Class
– Enumeration 119
Built-in data types
• Known as primary, fundamental or basic data
types.
125
User-defined data types
• Structures
• Classes
• Union
• Enumeration data types
126
User-defined data types
• Structure data type:
– Structures uses struct keywords to combine variables of
different data types in a single record.
– Syntax
• Struct[<struct name>]
{
<data type> <variable-name1>;
<data type> <variable-name2>;
} <sructure variable declaration>;
– Eg,
struct friend
{
char name[80];
int age, height;
}friendA;
127
User-defined data types
• class data type:
– The class keyword is used
– Syntax,
<class keyword><class-name> [<:base class list>]
{
<member variable list>
}
– Eg,
class circle
{
int radius; //data member
int area(void);//member function
} 128
User-defined data types
• union data type:
– Same as compared to struct, the only difference is that it
lets the user to declare variables that share same memory
space.
– Syntax
union [<union name>]
{
<data-type> <variable names>;
}[<union variables name>];
– Eg,
union charorint
{
char c;
int i;
}number; 129
User-defined data types
• Enumeration data type:
– enum is the keyword used.
– The programmer can declare new data type and define the
variables of these data types that can hold.
– Thus three values are restricted for this new data type
130
User-defined data types
• Syntax:
enum data-type {variable1,variable2}
• Example:
enum material{solid,liquid,gas};
enum logical{false,true};
enum logical{true=2,false=4};
132
Derived data type
• Pointers:
– A pointer is a memory variable that stores a
memory address.
133
Derived data type
• Examples:
int *x;
float *f;
char *y;
135
Derived data type
int main() funA()
{ {
…. ….
funA(); ….
…… return;
}
……..
funb()
funB()
….
{
….
….
}
….
….
return;
}
136
Derived data type
• In figure, funA() and funB() are two user
defined functions.
138
Derived data type
• References:
– C++ reference types declares with & operator.
– These are nearly identical but not exactly same as
pointer types.
– They declare aliases for object variables and allow
the programmer to use variable by reference.
– Eg, int a;
x=&a;
139
Statements
• A statement in a computer program carries out some
action.
• There are three types of statements are used in C++.
• Simple expression statement:
-consists of any valid C++ expression followed by a
semicolon
-A simple expression statements are used to
evaluate a group of expressions.
x=y;
sum=x+y;
140
Statements
• Compound statement:
– A group of valid C++ expressions placed within a { and }
statement is called a compound statement.
141
Statements
• Control statements:
– The control statement is used for the program flow
and to check the conditions of the given expression or
a variable or a constant.
143
Structure of C++ program
• It is a common practice to organize a program into
three separate files.
146
Structure of C++ program
• A program starts with preprocessor directives.
#include<iostream.h>
148
Structure of C++ program
• The namespace defines a scope for the identifiers that are
used in a program.
• This will bring all the identifiers defined in the std to the
current global scope.
• The syntax is
data-type main()
• The data-type void means the main() doesn’t return any value.
151
Structure of C++ program
• C++ introduces a new comment symbol //(double slash)
• All variables must be declared before they are used in the program.
• The statement cin>>number1; and
cin>>number2; are input statements and causes
the program to wait for the user to type in two numbers.
154
A Simple C++ program
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<“C++ is better than C \n”;
getch();
}
155
Input output streams
• Every program takes some data as input and
generates processed data as output.
156
Input output streams
• The data in the input stream can come from the
keyboard or another storage device.
157
Output operator – cout<<
159
Program to add two numbers
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a, b, sum;
cout<<“enter 2 numbers”;
cin>>a;
cin>>b;
sum= a+b;
cout<<“the sum =“<<sum;
getch();
}
160
Input operator – cin>>
The identifier cin is a predefined object in
C++ that corresponds to standard i/p stream
(keyboard).
161
Input using extraction operator
cin >> a
keyboard
162
Cascading of I/O operators
The multiple use of << or >> in one
statement is called cascading of I/O
operators
E.g. :-
cout<<“sum is “<<sum;
cin>>a>>b;
163