Module-1:
LECTURE-1
Introduction:
Programmers write instructions in various programming languages to perform their computation
tasks such as:
(i) Machine level Language
(ii) Assembly level Language
(iii) High level Language
Machine level Language :
Machine code or machine language is a set of instructions executed directly by a computer's central
processing unit (CPU). Each instruction performs a very specific task, such as a load, a jump, or an
ALU operation on a unit of data in a CPU register or memory. Every program directly executed by a
CPU is made up of a series of such instructions.
Assembly level Language :
An assembly language (or assembler language) is a low-level programming language for a computer,
or other programmable device, in which there is a very strong (generally one-to-one) correspondence
between the language and the architecture's machine code instructions. Assembly language is
converted into executable machine code by a utility program referred to as an assembler; the
conversion process is referred to as assembly, or assembling the code.
High level Language :
High-level language is any programming language that enables development of a program in much
simpler programming context and is generally independent of the computer's hardware architecture.
High-level language has a higher level of abstraction from the computer, and focuses more on the
programming logic rather than the underlying hardware components such as memory addressing and
register utilization,
The first high-level programming languages were designed in the 1950s. Now there are dozens of
different languages, including Ada , Algol, BASIC, COBOL, C, C++, JAVA, FORTRAN, LISP,
Pascal, and Prolog. Such languages are considered high-level because they are closer to human
languages and farther from machine languages. In contrast, assembly languages are considered low-
level because they are very close to machine languages.
The high-level programming languages are broadly categorized in to two categories:
(iv) Procedure oriented programming(POP) language.
(v) Object oriented programming(OOP) language.
PTAProcedure Oriented Programming Language
In the procedure oriented approach, the problem is viewed as sequence of things to be done such as
reading , calculation and printing.
Procedure oriented programming basically consist of writing a list of instruction or actions for the
computer to follow and organizing these instruction into groups known as functions.
Main program
Function-1 Funetion-2 Function-3
The disadvantage of the procedure oriented programming languages is:
1. Global data access
2. It does not model real word problem very well
3. No data hiding
Global data Global data
Function-1 Funetion-2 Function-3
Local data Local data Local data
Characteristics of procedure oriented programming:
Emphasis is on doing things(algorithm)
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
Function transforms data from one form to another.
Employs top-down approach in program design
aupene
PTALECTURE-2
Object Oriented Programing
“Object oriented programming as an epproach that provides a way of modularizing programs by
creating partitioned memory area for both data and functions that can be used as templates for
creating copies of such modules on demand”
Object A Object B
Data’ Data’
Functions |* *|_Functions
Object C
Functions
Data
Features of the Object Oriented srogramming
Emphasis is on doing rather than procedure.
programs are divided into what are known as objects.
Data structures are designed such that they characterize the objects.
Functions that operate on the data of an object are tied together in the data
structure.
Data is hidden and cen’t be accessed by external functions,
Objects may communicate with each other through functions.
New data and functions can be easily added.
Follows bottom-up ayproach in program design.
Beye
eae
PTALECTURE-3
BASIC CONCEPTS OF OBJECTS ORIENTED PROGRAMMING
Objects
Classes
Data abstraction and encapsulation
Inheritance
Polymorphism
Dynamic binding
A aypena
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 must handle,
The fundamental idea behind object oriented approach is to combine both data and function
into a single unit and these units are called objects.
The term objects means a combination of data and program that represent some real word
entity. For example: consider an example named Amit; Amit is 25 years old and his salary is 2500.
The Amit may be represented in a computer program as an object. The data part of the object would
be (name: Amit, age: 25, salary: 2500)
The program part of the object may be collection of programs (retrive of data, change age,
change of salary). In general even any user —defined type-such as employee may be used. In the
Amit object the name, age and salary are called attributes of the object.
Object: Student STUDENT
DATA Total
Name
Date-of-birth
Marks Average
FUNCTIONS
Total
Average Display
Display l
CLASS:
A group of objects that share common properties for data part and some program part are
collectively called as class.
In C ++ a class is a new data type that contains member variables and member functions that
operate on the variables.
PTADATA ABSTRACTION :
Abstraction refers to the act of representing essential features without including the back
ground details or explanations. Classes use the concept of abstraction and are defined as size, width
and cost and functions to operate on the attributes.
DATA ENCAPSALATION
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. These functions provide the interface between the objects data and
the program.
INHERITENCE :
Inheritance is the process by which objects of one class acquire the properties of another
class. In the concept of inheritance provides the idea of reusablity. This mean that we can add
additional features to an existing class with out modifying it. This is possible by desining a new class
will have the combined features of both the classes.
POLYMORPHISIM:
Polymorphism means the ability to take more than one form. An operation may exhibit different
instance, The behaviour depends upon the type of data used in the operation,
A language feature that allows a functicn or operator to be given more than one definition. The types
of the arguments with which the function or operator is called determines which definition will be
used.
Overloading may be operator overloading or function overloading.
It is able to express the operation of addition by a single operater say “+”. When this is possible you
use the expression x + y to denote the sum of x and y, for many different types of x and y; integers ,
float and complex no. You can even define the + operation for two strings to mean the concatenation
of the strings.
DYNAMIC BINDING :
Binding refers to the linking of a procedure call to the code to the executed in
response to the call. Dynamic binding means the code associated with a given procedure call is not
known untill the time of the call at run-time. It is associated with a polymorphic reference depends
upon the dynamic type of that reference.
9 PTCMESSAGE PASSING :
An object oriented progam consists of a set of objects that communicate with each
other.
A message for an object is a request for execution of a procedure and therefore will
invoke a function (procedure) in the receiving object that generates the desired result. Message
passing involves specifying the name of the object, the name of the function (message) and
information to be s
Employee . Salary (name)
Object Information
Message
10
PTALECTURE- 4
BENEFITS OF OOP:
Cop offers several benefits to both the program designer and the user, Object-oriented cortributes to
the solution of many problems associated with the development and quality of software products,
The principal advantages are
1. Through inheritance we can eliminate redundant code and extend the use of existing
classes.
2. We can build programs fron the standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving of
development time and higher productivity
3. This principle of data hiding helps the programmer to build secure programs that can’t be
invaded by code in other pacts of the program.
It is possible to have multiple instances of an object to co-exist with out any interference,
Itis easy to partition the work in a project based on objects.
Object-oriented systems car be easily upgraded from small to large systems.
Message passing techniques for communication between objects makes the interface
description with external systems much simpler.
8. Software complexity can be easily managed.
rs
APPLICATION OF OOP:
‘The most popular application of oops up to now, has been in the area of user interface
design such as windows. There are hundreds of windowing systems developed using oop
techniques.
Real business systems are often much more complex and contain many more objects
with complicated attributes and methods. Oop is useful in this type of applications because it
can simplify a complex problem, The promising areas for application of oop includes.
Real ~ Time systems
Simulation and modeling
Object oriented databases.
Hypertext,hypermedia and expertext,
Aland expert systems.
Neural networks and paralle! programming.
Dicision support and office automation systems.
CIM / CAM / CAD system.
SIA eke
u PTCLECTURE-5
Basics of C++
C ++ is an object oriened programming language, C ++ was developed by Jarney
Stroustrup at AT & T Bell lab, USA in early eighties. C ++ was developed from ¢ and simula 67
language. C ++ was early called *C with classes”
C++ introduces a new comment symbol //(double slash). Comments start with a
double slash symbol and terminate at the end of line. A comment may start any where in the line and
hat ever follows till the end of line is ignored. Note that there is no closing symbol.
The double slash comment is basically a single line comment. Multi line comments can be
written as follows:
//this is an example of
// e+ program
// thank you
The ¢ comment symbols /* ....*/ are still valid and more suitable for multi line comments.
/* this is an example of ++ program */
Output Operator:
The statement cout <<"Hello, world” displayed the string with in quotes on the screen. The identifier
cout can be used to display individual characters, strings and even numbers. It is a predefined object
that corresponds to the standard output stream, Stream just refers to a flow of data and the standard
Output stream normally flows to the screen display. The cout object, whose properties are defined in
iostream.h represents that stream. The insertion operator << also called the ‘put to” operator directs
the information on its right to the object on its left.
In C++ main ( ) returns an integer type value to the operating system. Therefore every main (
) in C+ should end with a return (0) statement, otherwise a warning or an error might occur.
Input Operator:
The statement
cin>> number 1;
is an input statement and causes. The program to wait for the user to type in a number. The number
keyed in is placed in the variable numberl. The identifier ein is a predefined object in C++ that
corresponds to the standard input stream, Here this stream represents the key board
The operator >> is known as get from operator. It extracts value from the keyboard
and assigns it to the variable on its right,
12
PTACascading Of VO Operato
cout<<"sum="<
>number!>>number2;
"<
using namespace std;
int main Q)
{
cout << "Hello World!";
return 0;
i
Output:-Hello World!
The first panel shows the source code for our first program, The second one shows the result of the
program once compiled and executed The way to edit and compile a program deperds on the
compiler you are using. Depending on whether it has a Development Interface or not and on its
version. Consult the compilers section and the manual or help included with your compiler if you
have doubts on how to compile a C++ console program.
The previous program is the typical program that programmer apprentices write for the first time,
and its result is the printing on screen of the "Hello World!" sentence. It is one of the simplest
programs that can be written in C++, bat it already contains the fundamental components that every
CH program has. We are going to look line by line at the code we have just written:
J/ my first program in C++
This is a comment line. All lines beginning with two slash signs (//) are considered comments and do
not have any effect on the behavior of the program. The programmer can use them to include short
explanations or observations within the source code itself. In this case, the line is a brief description
of what our program is,
#inelude
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code
lines with expressions but indications for the compiler’s preprocessor. In this case the directive
#include tells the preprocessor to include the iostream standard file. This specific file
(iostream) includes the declarations of the basic standard input-output library in C+, and it i
included because its functionality is going to be used later in the program.
using namespace std;
All the elements of the standard C++ library are declared within what is called a namespace, the
namespace with the name std. So in order to access its functionality we declare with this expression
that we will be using these entities. This line is very frequent in C++ programs that use the standard
library, and in fact it will be included in most of the source codes included in these tutorials.
int main ()
This line corresponds to the beginning of the definition of the main function, The main funetion is
the point by where all C+ programs start their execution, independently of its location within the
source code. It does not matter whether there are other functions with other names defined before or
after it — the instructions contained within this function's definition will always be the first ones to be
13
PTAexecuted in any C++ program. For that same reason, it is essential that all C++ programs have a main
function.
The word main is followed in the code by a pair of parentheses (()). That is because it is a function
declaration: In C++, what differentiates a function declaration from other types of expressions are
these parentheses that follow its name, Optionally, these parentheses may enclose a list of parameters
them
Right after these parentheses we can find the body of the main function enclosed in braces ({}).
What is contained within these braces is what the function does when it is executed.
cout <<" Hello World!";
This line is a C+ statement, A statement is a simple or compound expression that can actually
produce some effect, In fact, this statement performs the only action that generates a visible effect in
our first program.
cout represents the standard output stream in C++, and the meaning of the entire statement is to
insert a sequence of characters (in this case the Hello World sequence of characters) into the standard
output stream (which usually is the screen),
cout is declared in the iostream standard file within the std namespace, so that's why we needed to
include that specific file and to declare that we were going to use this specific namespace earlier in
our code.
Notice that the statement ends with a semicolon character (;). This character is used to mark the end
of the statement and in fact it must be included at the end of all expression statements in all C++
programs (one of the most common syntax errors is indeed to forget to include some semicolon after
a statement).
return 0;
The return statement causes the main function to finish. return may be followed by a retum code (in
our example is followed by the return code 0). A return code of 0 for the main function is generally
interpreted as the program worked as expected without any errors during its execution. This is the
most usual way to end a C+ console program.
You may have noticed that not all the lines of this program perform actions when the code is
executed. There were lines containing only comments (those beginning by //). There were lines with
directives for the compiler’s preprocessor (those beginning by #). Then there were lines that began
the declaration of a function (in this case, the main function) and, finally lines with statements (like
the insertion into cout), which were all included within the block delimited by the braces ({}) of the
main function
The program has been structured in different lines in order to be more readable, but in C++, we do
not have strict rules on how to separate instructions in different lines. For example, instead of
int main ()
{
cout <<" Hello World!";
return 0;
}
We could have written:
int main ()
{
cout << "Hello World!";
return 0;
}
All in just one line and this would have had exactly the same meaning as the previous code.
In C++, the separation between statements is specified with an ending semicolon (:) at the end of
each one, so the separation in different code lines does not matter at all for this purpose. We can
write many statements per line or write a single statement that takes many code lines. The division of
14 PTCcode in different lines serves only to make it more legible and schematic for the humans that may
read it
Let us add an additional instruction to our first program:
// my second program in C++
#include
using namespace std:
int main ()
t
cout << "Hello World! ";
cout << "I'm a C++ program";
return 0;
}
Output:-Hello World! I'm a C+ program
In this case, we performed two insertions into cout in two different statements. Once again, the
separation in different lines of code hes been done just to give greater readability to the program,
since main could have been perfectly valid defined this way:
int main ()
{
cout <<" Hello World! ";
cout <<" I'ma C+ program";
return 0;
}
We were also free to divide the code into more lines if we considered it more convenient:
int main ()
{
cout << "Hello World!";
cout << "I'm a C++ program";
return 0;
i
And the result would again have been exactly the same as in the previous examples.
Preprocessor directives (those that begin by #) are out of this general rule since they are not
statements. They are lines read and processed by the preprocessor and do not produce ary code by
themselves. Preprocessor directives must be specified in their own line and do not have to end with a
semicolon (:)
STRUCTURE OF C++ PROGRAM
© Include files
© Class declaration
© Class functions, definition
© Main function program
Example.
# include
class person
15 PTC{
char name[30];
int ag
void getdata(void)
void display(void);
ih
void person :: getdata ( void )
{
cout<<"enter name”;
cin>>name;
cout<<"enter age”;
cin>>age;
}
void display()
{
cout<<"\n name:”<>x;
sum=sum+x
4
float average;
average-sum/x;
cout< extraction operator
scope resolution operator
ut pointer to member declarator
* pointer to member operator
* pointer to member operator
Delete memory release operator
Endl line feed operator
New memory allocation operator
Sew field width operator
SCOPE RESOLUTION OPERATOR:
Like C,C+* is also a block-structured language. Block -structured language. Blocks and
scopes can be used in constructing programs, We know same variables can be declared in different
blocks because the variables declared in blocks arc local to that function,
Blocks in C++ are often nested.
Example:
Block2
Block1
+«—__]
Block2 contained in block | .Note that declaration in an inner block hides a declaration of the
same variable in an outer block and therefore each declaration of x causes it to refer to a different data object .
With in the inner block the variable x will refer to the data object declared there in.
25 PTCIn Che global version of a variable can't be accessed from with in the inner block.
C++ resolves this problem by introducing a new operator :: called the scope resolution operator .This can be
used to uncover a hidden variable.
Syntax: 21 variable—name;
Example:
#inelude
int m=10;
main()
{
int m=20;
{
int k-m;
int m=30;
cout<<"we are in inner block”;
cout<<"k="<
#include
inline float mul(foat x, float y)
{
return(x*y);
}
inline double dividouble p.double q)
{
return(p/q);
}
main()
t
float a=12.345;
float b-9.82;
cout<
Hinclude
mainQ
{
float amount;
float value(float p,int n,float r=0.15);
void printline(char ch="*’,int len=40);
printline( );
amount=value(5000.00,5);
cout<<"\n final value="<
int volume(double,int);
double volume( double , int );
double volume(longint ,int ,int);
main()
t
cout<
cout<>ml;
cout<<"enter 2nd subject mark:”;
cin>>m2;
4
void marks: :displaydata()
{
cout<<"Ist subject mark:"<
class set
t
int mn;
public:
void input(void);
void display (void);
void largest(void);
1
int set::largest (void)
{
iftm>n)
return m;
else
return n;
}
void set::input(void)
{
cout<<"input values of mand n:”;
cin>>m>>n;
}
void set::display( void)
{
cout<<"largestval
}
void main()
{
v<
class part
t
private:
int modelnum,partnum;
float cost;
public:
void setpart (int mm, int pn ,float e)
t
modelmim=mn;
partnum=pn;
cost=e;
}
void showpart ( )
Cout<
class distence
private:
public:
int feet;
float inches;
void setdist ( int ft, float in)
{
feet=
inches=in;
1
void getdist()
{
cout<<"enter feet:”;
cin>>feet;
cout<<"enter inches:”;
cin>>inches:
}
void showdist()
t
cout<< feet<<”
“inches«endl;
hs
void main( )
{
distance dl,d2;
dl.setdist(1 1,6.25);
2.getdata();
cout<
#inelude
class employee
t
private:
char name{20};
int age,sal;
public:
void getdata();
void putdata();
i
void employee : : getdata ()
{
cout<<"enter name
cin>>name;
cout<<"enter age :”;
cin>>age;
cout<<"enter salery:”;
cin>>sal;
return(0);
,
void employee : : putdata ()
{
cout<
#inelude
class emp
t
private:
char name{20};
int age,sal;
public:
void getdata( );
void putdata( );
hb
void emp :: getdata( )
t
coul<<"enter empname”:
cin>>nane;
cout<<"enter age:”<>age;
cout<<"enter salun :";
46 PTAvoid
cin>>sal;
}
‘emp :: putdata ()
t
cout<<"emp name:"<
#include
class sort
{
private:
int nm{30];
public;
void getdata();
void putdata();
i
void sort :: getdata()
{
int ijk;
cout<<"enter 10 n¢
si<10;i+4)
t
cin>>nmfi);
for(i
for(jritlj<10:j++)
{
iffnmfil>am{j))
void sort :: putdata()
{
int k;
for(k=0:k<10:k++)
t
cout<
#include
const int m=S0;
class items
{
int item_code{m];
float item_price{m];
int count;
void cnt(void) { count=0;}
void get_item(void);
void display_sum(void);
void remeve(void);
void display item(void);
void items :: get_item (void)
t
cout<<"enter itemcos
cin>> item_codecode];
cout<<"enter item cost:”;
cin>>item_price{count];
count ++;
}
Void items :: display _sum(void)
{
float sum=0;
fo:( int i-0:i>x;
switeh(x)
t
case 1: order.get_item(); break;
case 2: order.display_sum(); break;
cose 3: order.remove(); break;
case 4: order.display_item();break;
case 5: break;
default : cout<<"error
input; try again”;
50
PTALECTURE-17
STATIC_DATA MEMBER:
A data member of a class can be qualified as static . The
properties of a static member variable are similar to that of a static variable. A static member variable
has contain special characteristics.
Variable has contain special chacacteristics:~
1) tis initialized :o zero when the first object of its class is created.No other
initialization is permitted,
2) Only one copy of that member is created for the entire class and is shared by
all the objects of that class, no matter how many objects are created,
3) It is visible only with in the class but its life time is the entire program. Static
variables are normally used to maintain values common to the entire class.
For example a static data member can be used as a counter that records the
occurrence of all the objects.
int item :: coun:; // definition of static data member
Note that the type and seope of each static member variable must be defined outside
the class definition .This is necessary because the static data members are stored separately rather
than as a part of an object.
Example
‘Hinelude
class item
t
static int count; //count is static
int number;
public:
void getdatacint a)
{
number-a;
count;
}
void getcount(void)
t
cout<<"count:”;
cout<
class test
{
int code;
static int count; // static member variable
public:
void set(void)
{
code=+count;
}
void showcode(void)
{
cout<<"object member : “<
class time
t
int hours;
int minutes;
public:
void gettime(int h, int m)
{
hours=h;
minutes-m;
}
void puttime(void)
t
cout<< hours<<"hours and:”;
cout<
class sample
{
int a;
int b;
publie:
void setvalue( ) { a=25:b=40;}
friend float mean( sample s);
I
float mean (sample s)
t
return (float(s.a+s.b)/2.0);
}
int main()
{
PTAsample x;
x . setvalue( );
cout<<"mean value="<
public:
void setvelue(int x) {x= I; }
friend void max (xyz,abe);
h
class abe
{
int a;
publ
void setvelue( int i) {a=i; }
friend void max(xyz,abe);
void. max( xyz m, abe n)
t
iffm .x>=n.a)
‘cout=
class class-2;
class class-1
t
56 PTCint value |;
void indata( int a) { value=a; }
void display(void) { cout<
class account;
class account2
t
private:
int balance;
public:
account2( ) { balance=567; }
void showace2( )
{
cout<<"balanceinaccount2 is:”<
class complex
t
float x;
float y;
public:
void input( float real , float imag)
{
xereal;
yeimag;
}
friend complex sum( complex , complex);
void show ( complex );
i
complex sum (complex e1, complex ¢2)
t
complex ¢3;
€B.xel.xte2.x;
©3.yel ye
return ¢33}
void complex ::show (complex ¢)
{
cout<<¢,x<<" +] “< * ip;
cout<a;
The deferencing operator ->* is used as to accept a member when we use pointers to
both the object and the member. The dereferencing operator. .* is used when the object itself is used
with the member pointer. Note that * ip is used like a member name.
We can also design pointers to member functions which ,then can be invoked using
the deferencing operator in the main as shown below.
(object-name.* pointer-to-member function)
(pointer-to -object -> * pointer-to-member function)
The precedence of () is higher than that of |.* and ->* , so the parenthesis are
necessary,
61
PTADEREFERENCING OPERATOR:
#include
class M
void set_xy(int a,int b)
{
yb;
}
friend int sum(M);
hs
int sum (M m)
‘
int M :: * px= &M =: x; //pointer to member x
int Ms: * py- & m::yy/pointer to y
M* pm=&m;
int s-m.* px + pm->py;
return(s);
}
int main ()
t
Mm;
void(M::*pf)(int,int)=&M::set-xy;//pointer to function set-xy (n*pi\( 10,20);
invokes set-xy
cout<<"sum=:"<* pf)(30,40); // invokes set-xy
cout<<"sum="<
#inelude
class abe
t
private:
char nmi;
public:
abe ()
t
cout<<"enter your name:”;
cin>>nm;
}
void display( )
t
}
cout<
class integer
u
output:
object 1
m0
n=100
object?
m=25
integer(int,int);
void display( void)
cout<<"m=:"<
#include
class abe
{
private:
char nm [30];
int age;
public:
abe (){ }// default
abe ( char xf}, int y);
void get()
{
cout<<"enter your name:”;
cin>>nm;
cout<<” enter your age:
cin>>age;
ot
void display( )
t
cout<
#inelude
class sum
t
private;
int a;
int b;
int ¢;
float d;
double e;
public:
sum()t
cout<<"enter a;”;
cin>>a;
cout<<"enter b:”:
cin>>b;
cout<<"sur
}
sum(int aint b);
sum(int a, float d,double c);
= *<
class code
{
int id;public
code () { } “constructor
code (int a) { ida; } //eonstructor
code(code &x)
{
Id-x.id;
}
vi isplay( )
{
cout<
Hinelude
class string
t
char *name;
int eng
public:
string ()ew char [length+1]; /* one extra for \0 */
string( char *s) //constructor 2
{
length=strlen(s);
name=new char [length+1];
strepy(name,s);
}
void display(void)
{
cout<
int count=
class alpha
t
publie:
alpha( )
t
count ++;
cout<<"\n no of object created :”<
int x=I;
class abe
t
public:
abe( )
t
x5
cout<<"construct the no”<
#include
class stock2;
class stock
t
int code, item;
float price;
public:
stockl (int a, int b, float c)
{
code=a;
item=b;
price=c;
}
void disp( )
{
cout<<"eode"<