[go: up one dir, main page]

0% found this document useful (0 votes)
636 views143 pages

C++ Notes

C++ is an object-oriented programming language that was developed in the early 1980s as an extension of the C programming language with additional features like classes, inheritance, and polymorphism. Some key concepts of object-oriented programming in C++ include objects, classes, data abstraction and encapsulation, inheritance, and polymorphism. A C++ program structure includes include files, class declarations, class function definitions, and a main function.

Uploaded by

ephrem molla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
636 views143 pages

C++ Notes

C++ is an object-oriented programming language that was developed in the early 1980s as an extension of the C programming language with additional features like classes, inheritance, and polymorphism. Some key concepts of object-oriented programming in C++ include objects, classes, data abstraction and encapsulation, inheritance, and polymorphism. A C++ program structure includes include files, class declarations, class function definitions, and a main function.

Uploaded by

ephrem molla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 143

Compiled By Getinet

2010

C++

OBJECT ORIENTED PROGRAMMING


Conventional Programming using high level languages such as COBOL,
FORTRAN and C is commonly known as procedure oriented programming. In the
procedure oriented approach, the problem is view as a sequence of things to be done such
as reading, calculating and printing. A number of functions are written to accomplish these
tasks the primary focus is on function.

MAIN PROGRAM

FUNCTION 1 FUNCTION 2

FUNCTION 3

Procedure oriented programming basically consists of writing a list of instructions


for computer to follow and organized those instructions to groups known as functions.
While we concentrate on the development of functions, very little attention is given to the
data that are being used in various functions.

In a multi function program, many important data items are placed as global, so that
they may be accessed by all the functions. Each function may have its own local data.

RELATION BETWEEN FUNCTION AND DATA IN THE PROCEDURE


ORIENTED PROGRAMMING.
The major motivative factor in the invention of object oriented approach is to solve
some of the drawbacks in the procedural approach. Object oriented Programming treats
data as a critical element in the program development and does not allow 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 functions.
FUNCTION 2
FUNCTION1
LOCAL DATA
LOCAL DATA

OOP allows decomposing a problem in to a number of entities called objects and


then builds data and function around these entities. The data of an object can be accessed
only by the functions associated with that object. However function of an object can access
the functions of other objects.

1
Compiled By Getinet
2010

ORGANISATION DATA & FUNCTIONS IN OBJECT ORIENTED


PROGRAMMING.

Object A object B

DATA DATA

FUNCTIONS FUNCTIONS

OOP is the most recent concept in the programming. It is therefore important to have
a working definition of OOP. OOP is an approach that provides a way of modularity
programs by creating partitioned memory area for both data and functions. That is an object
is considered to be a partitioned area of computer memory that stores data and set of
operations that can access that data.

 CONCEPTS OF OBJECT ORIENTED PROGRAMMING

 OBJECTS: Objects are the basic runtime entities in an object-oriented system.


When a program is executed, the objects interact by sending messages to one another.

 CLASS: Class is a data type (user defined) to declare an object. That is objects are
variables of type class. Once a class has been defined, you can create any number of
objects belonging to that class.

 DATA ABSTRACTION AND ENCAPSULATION

Placing of data and functions into a single unit (class) is known as encapsulation. The
data is not accessible to the outside world and only those functions which are placed in
the class can access it, these functions provide the interface between objects data and
the program. The insulation of data from direct access by the program is called data
hiding.

Abstraction refers to the act of representing essential features without including the
background details and explanations. Classes use the concept of abstraction and defined
as a list of abstraction attributes. Since the classes use the concept of data abstraction
they are known as abstract data types (ADT).
INHERITANCE :

Inheritance is the process by which objects of one class acquire the properties of
objects of another class. In OOP the concept of inheritance provides the idea of reusability.
This means that we can add additional features of an existing class without modifying it.
This is possible by deriving a new class from the existing one. The new class will have the
combined features of both the classes.

2
Compiled By Getinet
2010

POLYMORPHISM :

Polymorphism means the ability to take more than one form. It places an important
role on allowing objects having different internal structures to show the same external
interface. This means that a general class of operations may be accessed in the same
manner eventhough specific actions associated with each operation may differ.

DYNAMIC BINDING :

Binding refers to the linking of a procedure call to the code to be executed in


response to the call. Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at the runtime. It is associated with
polymorphism and reference depends on the dynamic type of that reference.

C++

C++ is an object oriented programming language, initially named as "C with


classes". C++ was developed by Bjarne Stroustrup at "AT&T" bell laboratories in the early
of 1980's. In C++, the features of C and simula 67 are combined. There fore C++ is an
extension of C with a major addition of the class construct feature of "Simula 67". Since
the class was major addition to the original major C language, it is called as "C with
classes". However later in 1983, the name was changed to C++. The idea of C++ comes
from the 'C' increment operator "++", there by suggesting that C++ is an incremented
version of 'C'.
C++ is a superset of C. Therefore almost all C programs are also C++ programs.
The three most important facilities that C++ adds on to 'C' are classes, function overloading
and operator overloading. These features enables us to create abstract data types. Inherit
properties from existed data types and support polymorphism. Thus making C++ a truly
object oriented language.
STRUCTURE OF A C++ PROGRAM :
The programming structure of C++ is almost same as "C" except the class concept.
INCLUDE FILES
Class Declarations
Class Functions Definitions
main Function

<iostream.h>:
It is a header file consists of the entities (objects) related to input and output.
cout << : It is the output object in the C++ program.
Syntax : cout<<[message]<<[variable]<<[message]<<[variable]<<…….;
The operator "<<" is called an insertion or put to operator. It inserts or sends the
contents of a variable and / or specified messages on its right to the object to its left.
Ex:- cout<<”welcome”;
cin>> : It is the input object in C++ program.
Syntax : cin>>variable>>variable…….

3
Compiled By Getinet
2010

The operator ">>" is known as extraction or get from operator. It takes the value
from the keyboard and assigns it to the variable on it's right.
Ex:- cin>>a;

COMMENTS : (//)
C++ introduces a new comments symbol "//". Comments start with a double slash
(//) symbol and terminate at the end of a line. A comment may start anywhere in the line
and what ever follows till the end of the line is ignored.
Syntax : // comment

Example For A C++ Program

# include <iostream.h>
# include <conio.h>
void main()
{
clrscr();
cout<<"***WELCOME TO C++ PROGRAMMING***";

Read A Number And Write A Program To Find Out The Given Number Positive,
Negative Or Zero.

# include <iostream.h>
# include <conio.h>
void main()
{
int n;
clrscr();
cout<<"ENTER A NUMBER :";
cin>>n;
if(n>0)
cout<<"GIVEN NUMBER IS POSITIVE"<<n<<endl;
else if(n<0)
cout<<"GIVEN NUMBER IS NEGATIVE"<<n<<endl;
else
cout<<"GIVEN NUMBER IS ZERO"<<n<<endl;
getch();
}

Read Weekday Number And Print Weekday Name.

# include <iostream.h>
# include <conio.h>
void main()

4
Compiled By Getinet
2010

{
int n;
clrscr();
cout<<"ENTER WEEKDAY NUMBER (0-6) :";
cin>>n;
switch(n)
{
case 0:
cout<<"*SUNDAY*"<<endl;
break;
case 1:
cout<<"*MONDAY*"<<endl;
break;
case 2:
cout<<"*TUESDAY*"<<endl;
break;
case 3:
cout<<"*WEDNESDAY*"<<endl;
break;
case 4:
cout<<"*THURSDAY*"<<endl;
break;
case 5:
cout<<"*FRIDAY*"<<endl;
break;
case 6:
cout<<"*SATURDAY*"<<endl;
break;
default:
cout<<"INVALID WEEK DAY NUMBER"<<endl;
}
getch();
}

Read A Number To Print All The Natural Numbers Upto The Given Number
(Using 'For Loop').

# include <iostream.h>
# include <conio.h>
void main()
{
int n;
clrscr();
cout<<"ENTER A NUMBER "<<endl;
cin>>n;
for(int i=1;i<=n;i++)

5
Compiled By Getinet
2010

cout<<i<<"\t";
getch();
}

Program To Input Two Numbers And Print All Arithmetic Operations.

# include <iostream.h>
# include <stdio.h>
# include <conio.h>
void main()
{
int a,b,c,d,e,f,g;
float f;
clrscr();
cout<<"ENTER FIRST NUMBER :";
cin>>a;
cout<<"ENTER SECOND NUMBER :";
cin>>b;
c=a+b;
d=a-b;
e=a*b;
f=a/b;
g=a%b;
cout<<"ADDITION VALUE IS :"<<c<<endl;
cout<<"SUBTRACTION VALUE IS :"<<d<<endl;
cout<<"MULTIPLICATION VALUE IS :"<<e<<endl;
cout<<"DIVISION VALUE IS :"<<f<<endl;
cout<<"REMINDER VALUE IS :"<<g<<endl;
getch();
}
REFERENCE VARIABLES :

C++ introduces a new kind of variable known as the reference variable. A reference
variable provides an alias (Alternative name) for a previously defined variable. A reference
variable is created as follows:

Datatype &ref_var = variable;

A reference variable must be initialized at the time of declaration. This establishes the
correspondence between the reference and the data object that it names. Here the "&" is not
an address operator. The notation Datatype followed by "&" means reference to that
Datatype.

E.g.: int a=200;


int &b=a;
b=150;

6
Compiled By Getinet
2010

int &c=b;
c=25;

Example For Reference Variable

# include <stdio.h>
# include <conio.h>
# include <iostream.h>
void main()
{
int a=200;
int &b=a;
int &c=b;
clrscr();
cout<<"A VALUE IS :"<<a<<endl;
cout<<"B VALUE IS :"<<b<<endl;
cout<<"C VALUE IS :"<<c<<endl;
getch();
b=55;
cout<<"A VALUE IS :"<<a<<endl;
cout<<"B VALUE IS :"<<b<<endl;
cout<<"C VALUE IS :"<<c<<endl;
getch();
c=3500;
cout<<"A VALUE IS :"<<a<<endl;
cout<<"B VALUE IS :"<<b<<endl;
cout<<"C VALUE IS :"<<c<<endl;
getch();
}
FUNCTIONS WITH DEFAULT ARGUMENTS :

C++ allows to call a function without specifying all its arguments. In such cases the
function assigns a default value to the parameter which does not have a matching argument
in the function call. Default values are specified when the function is declared. The
compiler looks at the prototype to see how many arguments the function uses and alerts the
program for possible default values. A default value is specified in a manner similar to a
variable initialization. One important point to note is that only the trailing arguments can
have default arguments i.e. you must add default from right to left. It is not possible to
provide a default value to a particular argument in the middle of the argument list.

Ex: int add (int x, int y=0, int z=0);


int mul (int a=1,int b=20,int c=40)

Ex: add (10,20,30);

7
Compiled By Getinet
2010

add (10,20);
add (10);
add (); does not work, because there is no default value for argument x.

Another Example For Default arguments

# include <iostream.h>
# include <stdio.h>
# include <conio.h>
int add(int a,int b,int c=0,int d=0,int e=0)
{
return(a+b+c+d+e);
}
void main()
{
int m,n,p,q,r;
clrscr();
cout<<"ENTER ANY FIVE INTEGERS :"<<endl;
cin>>m>>n>>p>>q>>r;
cout<<"ADDITION OF 2 NUMBERS
ARE :"<<add(m,n)<<endl;
cout<<"ADDITION OF 3 NUMBERS ARE :"<<add(m,n,p)<<endl;
cout<<"ADDITION OF 4 NUMBERS ARE :"<<add(m,n,p,q)<<endl;
cout<<"ADDITION OF 5 NUMBERS ARE :"<<add(m,n,p,q,r)<<endl;
getch();
}
FUNCTION OVERLOADING :
Overloading refers to the use of the same thing for different purposes. C++ also
performs overloading of functions. This means you can use the same function name to
create functions that performs a variety of different tasks. This is known as function
polymorphism. OOP using the concept of function overloading you can design a family of
functions with one function name but with different arguments list. The function would
perform different operations depending on the argument list in the function call. The
correct function to be invoked is determined by choosing the number and type of
arguments, but not on the function’s return type.

Program For Function Overloading Operation

# include <iostream.h>
# include <stdio.h>
# include <conio.h>
int add(int a,int b) { return(a+b); }

8
Compiled By Getinet
2010

float add(float a,float b) { return(a+b); }

long add(long a,long b) { return(a+b); }

float add(int a,float b) { return(a+b); }

float add(float a,int b) { return(a+b); }

long add(int a,long b) { return(a+b); }

long add(long a,int b) { return(a+b); }

void main()
{
int x,y;
float f1,f2;
long l1,l2;
clrscr();
cout<<"ENTER TWO INTETEGER VALUES :";
cin>>x>>y;
cout<<"ENTER TWO FLOAT VALUES :";
cin>>f1>>f2;
cout<<"ENTER TWO LONG VALUES :";
cin>>l1>>l2;

cout<<"INTEGER VALUES ARE :"<<x<<"\t"<<y<<endl;


cout<<"FLOAT VALUES ARE :"<<f1<<"\t"<<f2<<endl;
cout<<"LONG VALUES ARE :"<<l1<<"\t"<<l2<<endl;

cout<<"SUM OF TWO INTEGER VALUES ARE :"<<add(x,y)<<endl;


cout<<"SUM OF TWO FLOAT VALUES ARE :"<<add(f1,f2)<<endl;
cout<<"SUM OF TWO LONG VALUES ARE :"<<add(l1,l2)<<endl;
cout<<"SUM OF TWO INTEGER & FLOAT VALUES
ARE :"<<add(x,f2)<<endl;
cout<<"SUM OF TWO FLOAT & INTEGER VALUES
ARE :"<<add(f1,y)<<endl;
cout<<"SUM OF TWO INTEGER & LONG VALUES
ARE :"<<add(x,l2)<<endl;
cout<<"SUM OF TWO LONG & INTEGER VALUES
ARE :"<<add(l1,y)<<endl;
getch();
}

STRUCTURES

9
Compiled By Getinet
2010

C++ supports all the features of structures as defined in C. But C++ extended its
capabilities further to suit it's OOP philosophy. In C++ structure can have both variables
and functions as members as private so that they can not be accessed directly by the
external functions. In C++ the structure names are standalone and can be used like any
other type names. That is the keyword struct can be omitted in the declaration of structure
variables.

E.g.:
struct employ
{
int eno,bs,da,hra,pf;
char ena[10];
};
struct employ emp; // C declaration
employ emp //C++ declaration
emp.eno,emp.ena,emp.bs,emp.da,
emp.hra,emp.pf

Example For Structure Program.

# include <iostream.h>
# include <stdio.h>
# include <conio.h>
void main()
{
struct stud
{
int sno,tf,fp;
char sna[10],cr[10];
};
clrscr();
stud s;
cout<<"\nENTER STUDENT'S NUMBER :";
cin>>s.sno;
cout<<"\nENTER STUDENT'S NAME :";
cin>>s.sna;
cout<<"\nENTER COURSE NAME :";
cin>>s.cr;
cout<<"\nENTER TOTAL FEES :";
cin>>s.tf;
cout<<"\nENTER PAID FEES :";
cin>>s.fp;
getch();
int due;
due=s.tf-s.fp;
cout<<"STUDENT'S NUMBER IS :"<<s.sno<<endl;

10
Compiled By Getinet
2010

cout<<"STUDENT'S NAME IS :"<<s.sna<<endl;


cout<<"COURSE NAME IS :"<<s.cr<<endl;
cout<<"TOTAL FEES IS :"<<s.tf<<endl;
cout<<"PAID FEES IS :"<<s.fp<<endl;
cout<<"DUE FEES IS :"<<due<<endl;
getch();
}
CLASSES

A class is a way to bind the data and its associated functions together. It allows the
data (and functions) to be hidden if necessary from external use. When defining a class, we
are creating a new abstract data type that can be treated like any other built in data type.

Generally a class specification has two parts.


1.Class declaration.
2.Class function definition.

The class declaration describes the type and scope of its members. The class
function definitions describe how the class functions are implemented.

The general form of a class declaration is:


class class_name
{
private:
variable declaration;
public:
variable declaration;
function declaration;
};
The key word class specifies that what follows is an abstract data type class_name.
The body of a class is enclosed in braces ({ }) and terminated by a semicolon. The class
body contains the declaration of variables and functions. These variables and functions are
collectively called members. They are usually grouped under two sections namely private
and public. To denote which of the members are private and ,which of them are the public,
the keywords private and public can be used. The keywords private and public are known
as visibility labels.
The members that have been declared as private can be accessed only with in the class. On the
other hand public members can be accessed from outside the class also. By default all the members of a
class are private. If both the labels are missing, then the class is completely hidden from the outside the
world and does not serve any purpose. The variables declared inside the class are known as data
members and functions are known as member functions. Only the public member functions can have
access to private data members and private functions. However the public members can be accessed
outside the class.

OBJECTS

11
Compiled By Getinet
2010

Once the class has been declared, you can create variables of that type by using the class name.
In C++ the class variables are known as objects.
ACCESSING CLASS MEMBERS
The following format is used for calling the member functions or data members if
they are public.
Object name.data member
Object name.member function (argument list);

Example For Class Program

# include <iostream.h>
# include <stdio.h>
# include <conio.h>
class sample
{
int a; int b;
public:
int c;
void input(int x,float y) //public member function
{
a=x;
b=y;
}
void display() //public member function
{
cout<<"A VALUE IS :"<<a<<endl;
cout<<"B VALUE IS :"<<b<<endl;
}
};
void main()
{
sample s; //object declaration
s.input(352,225.54);
s.c=4444;
clrscr();
s.display();
cout<<"C VALUE IS :"<<s.c<<endl;
getch();
}

Read Employ Number, Employ Name, Grade, Basic Salary And Calculate DA, HRA,
PF, IT, Gross Salary And Net Salary.

# include <iostream.h>
# include <stdio.h>
# include <conio.h>

12
Compiled By Getinet
2010

class employ
{
int eno;
char ename[20],eg;
float bs;
public:
void accept()
{
cout<<"\nENTER EMPLOY NUMBER :";
cin>>eno;
cout<<"\nENTER EMPLOY NAME :";
cin>>ename;
cout<<"\nENTER EMPLOY'S BASIC SALARY :";
cin>>bs;
cout<<"\nENTER EMPLOY'S GRADE A/B/C";
cin>>eg;
}
void display()
{
float da,hra,pf,it,gs,ns;
switch(eg)
{
case 'a':
da=bs*.20;
hra=bs*.25;
pf=bs*.1;
it=bs*.01;
break;
case 'b':
da=bs*.16;
hra=bs*.22;
pf=bs*.01;
it=bs*.06;
break;
default :
da=bs*.13;
hra=bs*.15;
pf=bs*.6;
it=bs*.06;
}
gs=bs+da+hra;
ns=bs-(pf+it);
cout<<"Employ Number Is :"<<eno<<endl;
cout<<"Employ Name is :"<<ename<<endl;
cout<<"Basic Salary is :"<<bs<<endl;
cout<<"Employ's Grade is :"<<eg<<endl;

13
Compiled By Getinet
2010

cout<<"Daily Allowances are :"<<da<<endl;


cout<<"House Rent Allowances :"<<hra<<endl;
cout<<"Provident Fund :"<<pf<<endl;
cout<<"Income Tax :"<<it<<endl;
cout<<"Gross Salary is :"<<gs<<endl;
cout<<"Net Salary is :"<<ns<<endl;
}
};
void main()
{
employ emp;
clrscr();
emp.accept();
clrscr();
emp.display();
getch();
}

Read Student Number, Student Name, 3 Subjects' Marks. Write A Program To Calculate
Total Marks, Avg. Marks And Result Based On The Following Conditions.

# include <iostream.h>
# include <stdio.h>
# include <conio.h>
# include <string.h>
class student
{
int sno,m1,m2,m3;
char sname[10];
public:
void input()
{
cout<<"ENTER STUDENT NUMBER :";
cin>>sno;
cout<<"ENTER STUDENT NAME :";
cin>>sname;
cout<<"ENTER THREE SUBJECTS' MARKS :";
cin>>m1>>m2>>m3;
}
int total()
{
return(m1+m2+m3);
}
void output()
{
cout<<"STUDENT NUMBER IS :"<<sno<<endl;

14
Compiled By Getinet
2010

cout<<"STUDENT NAME IS :"<<sname<<endl;


cout<<"MARRKS IN THREE SUBJECTS' ARE :"<<m1<<m2<<m3<<endl;
}
};
void main()
{
student st;
int tm,am;
char res[20];
clrscr();
st.input();
tm=st.total();
am=tm/3;
if(am>=70)
strcpy(res,"DISTINCTION");
else if(am>=60 && am<70)
strcpy(res,"FIRST CLASS");
else if(am>=50 && am<60)
strcpy(res,"SECOND CLASS");
else if(am>=35 && am<50)
strcpy(res,"THIRD CLASS");
else
strcpy(res,"FAILED");
clrscr();
st.output();
cout<<"TOTAL MARKS ARE :"<<tm<<endl;
cout<<"AVERAGE MARKS ARE :"<<am<<endl;
cout<<"RESULT OBTAINED :"<<res<<endl;
getch();
}

Read Employ Number, Employ Name, Grade, Basic Salary And Calculate Da, Hra, Pr,
It, Gross Salary And Net Salary.
(By Using Classes.)

# include <iostream.h>
# include <stdio.h>
# include <conio.h>
class employ
{
int eno;
char ena[20],eg;
float bs;
public:
void accept()
{

15
Compiled By Getinet
2010

cout<<"ENTER EMPLOY NUMBER :";


cin>>eno;
cout<<"ENTER EMPLOY NAME :";
cin>>ena;
cout<<"ENTER BASIC SALARY :";
cin>>bs;
cout<<"ENTER EMPLOY GRADE A/B/C :";
cin>>eg;
}
char getgrade()
{
return(eg);
}
float getbs()
{
return(bs);
}
void display()
{
cout<<"EMPLOY NUMBER IS :"<<eno<<endl;
cout<<"EMPLOY NAME IS :"<<ena<<endl;
cout<<"EMPLOY BASIC SALARY IS :"<<bs<<endl;
cout<<"EMPLOY GRADE IS :"<<eg<<endl;
}
};
void main()
{
employ emp; //object declaration for employ class
char egrade;
float da,hra,pf,it,gs,ns,bsal;
emp.accept();
egrade=emp.getgrade();
bsal=emp.getbs();
switch(egrade)
{
case 'A':
da=bsal*.20;
hra=bsal*.25;
pf=bsal*.01;
it=bsal*.03;
break;
case 'B':
da=bsal*.16;
hra=bsal*.20;
pf=bsal*.008;
it=bsal*.006;

16
Compiled By Getinet
2010

break;
case 'C':
da=bsal*.13;
hra=bsal*.15;
pf=bsal*.06;
it=bsal*.05;
break;
}
clrscr();
gs=bsal+da+hra;
ns=gs-(pf+it);
emp.display();
cout<<"DA IS :"<<da<<endl;
cout<<"HRA IS :"<<hra<<endl;
cout<<"PF IS :"<<pf<<endl;
cout<<"IT IS :"<<it<<endl;
cout<<"GROSS SALARY IS :"<<gs<<endl;
cout<<"NET SALARY IS :"<<ns<<endl;
getch();
}

FUNCTION DEFINITIONS OUTSIDE THE CLASS

Member functions which are declared inside a class have to be defined separately
outside the class. They should have a function definition outside the class as
returntype class_name :: function_name(arguments list)
{
function body;
}
The membership label class_name :: tells the compiler that the function belongs to
the class class_name.That is the scope of the function is restricted to the class_name
specified in the headerline.
The symbol "::" is called Scope Resolution operator.

Read Sales Man Number, Name, Product Code And Number Of Units. Write A Program
To Calculate The Sales Amount And Commission Based On The Following Conditions:
SAMT COMMISSION
>=10000 15%
>=7500 & <10000 12%
>=5000 & <7500 10%
<5000 05% On Sales Amount.

17
Compiled By Getinet
2010

FUNCTION DEFINITION OUTSIDE THE CLASS.

# include <iostream.h>
# include <conio.h>
class sales
{
int sno,nou,pc;
char sna[20];
public:
void input();
void output();
int getnou();
int getpc();
};
void sales::input()
{
cout<<"ENTER SALESMAN NUMBER :";
cin>>sno;
cout<<"ENTER SALES MAN NAME :";
cin>>sna;
cout<<"ENTER PRODUCT CODE :";
cin>>pc;
cout<<"ENTER NUMBER OF UNITS :";
cin>>nou;
}
void sales::output()
{
cout<<"SALES MAN NUMBER IS :"<<sno<<endl;
cout<<"SALES MAN NAME IS :"<<sna<<endl;
cout<<"PRODUCT CODE IS :"<<pc<<endl;
cout<<"NUMBER OF UNITS ARE :"<<nou<<endl;
}
int sales::getnou()
{
return(nou);
}
int sales::getpc()
{
return(pc);
}
void main()
{
sales s;
int units,rate,samt,comm,pcode;
clrscr();
s.input();

18
Compiled By Getinet
2010

pcode=s.getpc();
units=s.getnou();
if(pcode==1)
rate=25;
else if(pcode==2)
rate=35;
else
rate=50;
samt=units*rate;
if(samt>=10000)
comm=samt*.15;
else if(samt>=7500)
comm=samt*.12;
else if(samt>=5000)
comm=samt*.1;
else
comm=samt*0.6;
clrscr();
s.output();
cout<<"RATE PER UNIT IS :"<<rate<<endl;
cout<<"SALES AMOUNT IS :"<<samt<<endl;
cout<<"COMMISSION IS :"<<comm<<endl;
getch();
}
OBJECT ARRAYS :
We know that an array can be of any data type including struct, similarly we can
also have arrays of variables that are of the type class. Such variables are called array of
objects.

class employ
{
char name[10];
int age;
public:
void inputdata();
void outputdata();
};
ex:-
employ emp[5];
The array emp contains five objects, namely emp[0], emp[1], emp[2], emp[3],
emp[4] of type employ class.
Since the array of objects behaves like any other array, we can use the usual array
accessing methods to access individual elements and then the dot member operator to
access the member function.

E.g.: emp[0].age = 25;

19
Compiled By Getinet
2010

strcpy(emp[0].name,“hari”);
emp[0].inputdata();
emp[0].outputdata();
The array of objects is stored inside the memory in the same way as the
multidimensional array.

Create A Class With The Name Bank And Create An Array With 5 Cells And Accept
Data And Print Data.
Example For An Object Arrays.

# include <stdio.h>
# include <iostream.h>
# include <conio.h>
class bank
{
int acno,cbal;
char cname[20];
public:
void input();
void output();
};
void bank::input()
{
cout<<"ENTER A/C NUMBER :";
cin>>acno;
cout<<"ENTER CUSTOMER NAME :";
cin>>cname;
cout<<"ENTER CURRENT BALANCE :";
cin>>cbal;
}
void bank::output()
{
cout<<"ACCOUNT NUMBER IS :"<<acno<<endl;
cout<<"CUSTOMER NAME IS :"<<cname<<endl;
cout<<"CURRENT BALANCE IS :"<<cbal<<endl;
}
void main()
{
int i;
bank b[5];
for(i=0;i<5;i++)
{
cout<<"ENTER VALUES FOR CELL :"<<i<<endl;
b[i].input();
}
clrscr();

20
Compiled By Getinet
2010

for(i=0;i<5;i++)
{
cout<<"THE VALUES OF THE CELL :"<<i<<endl;
b[i].output();
getch();
}
}
FRIEND FUNCTIONSSDD
C++ allows a common function to be made friendly with two or more classes.
There by allowing the function to have access to the private data of these classes, such a
function need not be a member of any of these classes, declare the function as the friend to
the class.
Declaration:
class sample
{
private:
member declaration;
public:
member function declaration;
//friend function declaration
friend return type
function(arguments);
};
The function declaration should be preceded by the keyword "friend". The function
definition does not use the key word friend or the scope resolution operator "::". The
functions that are declared with the key word friend are known as friend functions. A
function can be declared as a friend in any number of classes.
Special characteristics of a friend functions.
1. It is not in the scope of a class to which it has been declared as friend.
2. Unlike member functions, it can not access the member names directly and has
to use an object name and dot (.) member ship operator with each member
name.
3. Usually a friend function has objects as arguments.
4. Friend function can take objects as arguments and can also return the objects.

Friend Function Example.

# include <iostream.h>
# include <conio.h>
class sample;
class myclass
{
int a;
public:
void input()
{

21
Compiled By Getinet
2010

cout<<"ENTER VALUE FOR A:";


cin>>a;
}
void output()
{
cout<<"A VALUE IS :"<<a<<endl;
}
friend int getsum(myclass m,sample a)
};
class sample
{
int x;
public:
void accept()
{
cout<<"ENTER A VALUE :";
cin>>x;
}
//friend function declaration
friend int getsum(myclass m,sample s)
};
int getsum(myclass m,sample s)
{
return(m.a+s.x);
}
void main()
{
myclass c;
sample d;
int t;
clrscr();
c.input();
d.accept();
t=getsum(c,d); //friend function calling
clrscr();
c.output();
d.accept();
cout<<"TOTAL VALUE IS :"<<t<<endl;
getch();
}

2nd Example For A Friend Function.

# include <iostream.h>
# include <stdio.h>
# include <conio.h>

22
Compiled By Getinet
2010

class allow;
class ded;
class employ
{
int eno,bs;
char ena[10];
public:
void accept()
{
cout<<"ENTER EMPLOY NUMBER :";
cin>>eno;
cout<<"ENTER EMPLOY NAME :";
cin>>ena;
cout<<"ENTER BASIC SALARY :";
cin>>bs;
}
friend void calc_sal(employ e,allow a,ded d);
};
class allow
{
int da,hra,cca;
public:
void getallow()
{
cout<<"ENTER DA, HRA, CCA :"<<endl;
cin>>da>>hra>>cca;
}
friend void calc_sal(employ e,allow a,ded d);
};
class ded
{
int pf,it;
public:
void getded()
{
cout<<"ENTER PF, IT :"<<endl;
cin>>pf>>it;
}
friend void calc_sal(employ e,allow a,ded d);
};
void calc_sal(employ e,allow a,ded d)
{
int gs,ns,tall,tded;
tall=d.pf+d.it+a.cca;
tded=d.pf+d.it;
gs=e.bs+tall;

23
Compiled By Getinet
2010

ns=gs-tded;
clrscr();
cout<<"ENTER EMPLOY NUMBER :"<<e.eno<<endl;
cout<<"ENTER EMPLOY NAME :"<<e.ena<<endl;
cout<<"ENTER BASIC SALARY :"<<e.bs<<endl;
cout<<"DA IS :"<<a.da<<endl;
cout<<"HRA IS :"<<a.hra<<endl;
cout<<"CCA IS :"<<a.cca<<endl;
cout<<"PF IS :"<<d.pf<<endl;
cout<<"IT IS :"<<d.it<<endl;
cout<<"GROSS SALARY IS :"<<gs<<endl;
cout<<"NET SALARY IS :"<<ns<<endl;
}
void main()
{
employ emp;
allow all;
ded s;
clrscr();
emp.accept();
all.getallow();
s.getded();
calc_sal(emp,all,s);
getch();
}

Friend Functions With Objects As Arguments And Return Type.

# include <iostream.h>
# include <conio.h>
class test;
class sample
{
int a;
float b;
public:
void input()
{
cout<<"ENTER ANY INTEGER AND FLOAT VALUES :"<<endl;
cin>>a>>b;
}
void display()
{
cout<<"A VALUE IS :"<<a<<endl;
cout<<"B VALUE IS :"<<b<<endl;
}

24
Compiled By Getinet
2010

friend sample setsum(sample x,test y);


};
class test
{
int m;
float n;
public:
void accept()
{
cout<<"ENTER INTEGER AND FLOAT :"<<endl;
cin>>m>>n;
}
void print()
{
cout<<"M VALUE IS :"<<m<<endl;
cout<<"N VALUE IS :"<<n<<endl;
}
friend sample setsum(sample x,test y);
};
sample setsum(sample x,test y)
{
sample r;
r.a=x.a+y.m;
r.b=x.b+y.n;
return r;
}
void main()
{
sample s,p;
test t;
clrscr();
s.input();
t.accept();
clrscr();
p=setsum(s,t);
cout<<"VALUE OF FIRST OBJECT IS :"<<endl;
s.display();
cout<<"VALUE OF SECOND OBJECT IS :"<<endl;
t.print();
cout<<"VALUE OF RESULT OBJECT IS :"<<endl;
p.display();
getch();
}
CONSTRUCTORS

25
Compiled By Getinet
2010

A constructor is a special member function whose task is to initialize the objects of


a class. The constructor is invoked whenever an object of associated class is created. It is
called constructor, because it constructs the values of data members of the class.
Constructors are 3 types.
1. Default construtor (or) No argument constructor.
2. Constructor with arguments (or) Parameterized constructor.
3. Constructor overloading
A constructor is declared as follows.
class class_name
{
members;
public:
class_name(arguments) //constructor
{
statements;
}
};
Special characteristics of a Constructor function.
1.They are invoked automatically when the objects are created.
2.They do not have return types not even void.
3.Like C++ functions they can have default arguments.
4.The constructor name is same as the class name in the class.

Example For Constructors.

# include <iostream.h>
# include <stdio.h>
# include <conio.h>
class test
{
int a;
float b;
long c;
public:
test() //constructor function
{
a=230;
b=654.13;
c=54865;
}
void output()
{
cout<<"INTEGER VALUE IS :"<<a<<endl;
cout<<"FLOAT VALUE IS :"<<b<<endl;
cout<<"LONG VALUE IS :"<<c<<endl;
}

26
Compiled By Getinet
2010

};
void main()
{
clrscr();
test t,s,r;
clrscr();
cout<<"VALUES OF T ARE :"<<endl;
t.output();
cout<<"VALUES OF S ARE :"<<endl;
s.output();
cout<<"VALUES OF R ARE :"<<endl;
r.output();
getch();
}

Example For Constructor Function.

# include <iostream.h>
# include <conio.h>
class stud
{
int sno,tf,fp,due;
char sna[10],cou[10];
public:
stud()
{
cout<<"enter student's number :";
cin>>sno;
cout<<"enter student's name :";
cin>>sna;
cout<<"enter course name :";
cin>>cou;
cout<<"enter total fee is :";
cin>>tf;
cout<<"enter fee paid :";
cin>>fp;
due=tf-fp;
}
void output()
{
cout<<"student's number is :"<<sno<<endl;
cout<<"student's name is :"<<sna<<endl;
cout<<"course name is :"<<cou<<endl;
cout<<"total name is :"<<tf<<endl;

27
Compiled By Getinet
2010

cout<<"fee paid is :"<<fp<<endl;


cout<<"due fee is :"<<due<<endl;
}
};
void main()
{
clrscr();
stud s,t,u;
clrscr();
cout<<"values of s"<<endl;
s.output();
cout<<"values of t"<<endl;
t.output();
cout<<"values of u"<<endl;
u.output();
getch();
}

Example For Constructor With Arguments.

# include <iostream.h>
# include <conio.h>
# include <string.h>
class sales
{
int sno,samt;
char sna[10];
public:
sales(int a,char n[],int b)
{
sno=a;
strcpy(sna,n);
samt=b;
}
void output()
{
cout<<"SALES MAN NUMBER IS :"<<sno<<endl;
cout<<"SALES MAN NAME IS :"<<sna<<endl;
cout<<"SALES AMOUNT IS :"<<samt<<endl;
}
};
void main()
{
clrscr();
sales t(100,"RAVI",2500);
sales b=sales(101,"KIRAN",3000);

28
Compiled By Getinet
2010

cout<<"VALUES OF T :"<<endl;
t.output();
cout<<"VALUES OF B :"<<endl;
b.output();
getch();
}
DESTRUCTORS:

A destructor as the name implies, is used to destroy the objects that have
been created by a constructor. Like a constructor, the destructor is also a member function
whose name is same as the class name and is preceeded by a tilde(~) symbol. A destructor
neither takes any arguments nor return any value. It will be invoked implicitly by the
compiler on exit from the program to clean up the storage that is no longer accessible.

OPERATOR OVERLAODING :

Operator overloading is one of the many exiting features of C++ language. It is an


important technique that has enhanced the power of extensibility of C++. C++ has the
ability to provide the operator with a special meaning for a data type. The mechanism of
giving such special meanings to an operator is known as operator overloading.
Operator overloading provides a flexible option for the creation of new definition
for most of the C++ operators. We can almost create a new language of our own by the
creative use of the function and operator overloading techniques.
To define an additional task to an operator, we must specify what it means in
relation to the class to which the operator is applied. This is done with help of a special
function, called operator function, which describes the task. The general form of an
operator function is:
return_type operator op(argument list)
{
function_body();
}
Where return type is the type of value returned by the specified operation and op is
the operator being overloaded. The keyword "operator" precedes the "op". Operator op is
the function name.
this Pointer:
C++ uses a unique keyword called "this". To represent an object that invokes a
member function. "this" is a pointer that points to the object for which this function was
called. The unique pointer is automatically passed to a member function when it is called.
The pointer "this" acts as an implicit argument to all the member functions.
Note:- we can’t over load ‘ . :: -> ‘

Example For Operator Overloading Of Unary Operator:

# include <iostream.h>
# include <conio.h>

29
Compiled By Getinet
2010

class exam
{
int a;
float b;
long c;
public:
exam() //constructor function
{
a=10;
b=25.65;
c=42500;
}
exam operator ++() //operator overloading function
{
a+=100;
b+=100;
c+=100;
return *this;
}
void print()
{
cout<<"A VALUE IS :"<<a<<endl;
cout<<"B VALUE IS :"<<b<<endl;
cout<<"C VALUE IS :"<<c<<endl;
}
};
void main()
{
exam e;
int x=15;
clrscr();
cout<<"VALUE BEFORE FUNCTION CALLING :"<<endl;
e.print();
cout<<"x value is :"<<x<<endl;
++e; //operator function calling
x++;
cout<<"value after function calling "<<endl;
e.print();
cout<<"x value is :"<<x<<endl;
getch();
}

Output: Values before function calling


A value is 10, B value is 25.65,C value is 42000 and X value is 15.

Values after function calling

30
Compiled By Getinet
2010

A value is 110, B value is 125.65,C value is 142000 and X value is 16.

Example Program For Operator Overloading A Binary Operator "+":

# include <iostream.h>
# include <stdio.h>
# include <conio.h>
class sample
{
int a,b;
float m,n;
public:
void get_data()
{
cout<<"ENTER ANY TWO INTEGERS AND TWO FLOATS :";
cin>>a>>b>>m>>n;
}
void print()
{
cout<<"FIRST INTEGER IS :"<<a<<endl;
cout<<"SECOND INTEGER IS :"<<b<<endl;
cout<<"FIRST FLOAT IS :"<<m<<endl;
cout<<"SECOND FLOAT IS :"<<n<<endl;
}
//operator overloading function
sample operator +(sample s)
{
sample t;
t.a=this->a+s.a;
t.b=this->b+s.b;
t.m=this->m+s.m;
t.n=this->n+s.n;
return(t);
}
};
void main()
{
sample p,q,r;
clrscr();
p.get_data();
q.get_data();
clrscr();
r=p+q; //function calling
cout<<"values of first object :"<<endl;
p.print();
cout<<"values of second object :"<<endl;

31
Compiled By Getinet
2010

q.print();
cout<<"addition object values are :"<<endl;
r.print();
getch();
}

Example Program For Overloading A Binary Operator "*":

# include <iostream.h>
# include <stdio.h>
# include <conio.h>
class sales
{
int sno,nou;
char sna[10];
public:
sales() //constructor
{
cout<<"ENTER SALES MAN NUMBER :"<<endl;
cin>>sno;
cout<<"ENTER SALES MAN NAME :"<<endl;
cin>>sna;
cout<<"ENTER NUMBER OF UNITS :"<<endl;
cin>>nou;
}
void print()
{
cout<<"SALES MAN NUMBER IS :"<<sno<<endl;
cout<<"SALES MAN NAME IS :"<<sna<<endl;
cout<<"NUMBER OF UNITS ARE :"<<nou<<endl;
}
int operator *(int n)
{
return(nou * n);
}
};
void main()
{
sales s;
int rpu,samt;
clrscr();
cout<<"ENTER RATE PER UNIT :"<<endl;
cin>>rpu;
clrscr();
samt=s*rpu; //operator function calling
s.print();

32
Compiled By Getinet
2010

cout<<"RATE PER UNIT IS :"<<rpu<<endl;


cout<<"SALES AMOUNT IS :"<<samt<<endl;
getch();
}
POINTERS IN C++
In C++ a pointer can point to an object created by a class.
For example item x;
Where item is a class and x is an object defined to be of type item. Similarly we can
define a it_ptr of type item as follows

item *it_ptr;
Object pointers are useful in creating objects at runtime. We can also use an object
pointer to access the public members of an object.
MEMORY MANAGEMENT OPERATORS.
C uses malloc() and calloc() functions to allocate memory dynamically at runtime.
Similarly it uses the function free() to free dynamically allocated memory. Although C++
supports these functions, it also defines two unary operators 'new' and 'delete' that perform
the task of allocating and freeing the memory in a better and easier way. Since these
operators manipulate memory on the free store, these are also known as free store
operators.

The 'new' operator can be used to create objects of any type.


Syntax: pointer_variable = new datatype

Here pointer_variable is a pointer of type datatype. The new operator allocates


sufficient memory to hold a data objects of TYPE datatype and return the address of the
object. The datatype may be any valid datatype. The pointer variable holds the address of
the memory space allocated.

E.g. int *p;


float *q;
p = new int[10];
q = new float [20];
Where p is a pointer of type int and q is a pointer of type float.
When a data object is no longer needed, it is destroyed to release the memory space
for reuse, in that case we can use 'delete' operator.

Syntax: delete pointer_variable;


The pointer_variable is the pointer that points to a data object created with new
operator.
E.g. delete p;
delete q;

sales s;
sales *q;
q =&s;

33
Compiled By Getinet
2010

qinput() or sales.input();
qprint() or sales.print();

Example Program For Dynamic Memory Allocation.

# include <iostream.h>
# include <stdio.h>
# include <conio.h>
void main()
{
int n,*a,*p;
clrscr();
cout<<"ENTER NUMBER OF CELLS";
cin>>n;
a=new int[n];
for(p=a;(p-a)<n;p++)
{
cout<<"ENTER ANY VALUE TO ARRAY :";
cin>>*p;
}
clrscr();
for(p=a;(p-a)<n;p++)
{
printf("THE CELL NUMBER IS %d\t:",(p-a));
printf("THE CELL ADDRESS IS \n:",p);
cout<<"VALUE OF ARRAY :"<<*p<<endl;
}
delete a;
getch();
}

Example Program For Object Arrays With Dynamic Memory Allocation.

# include <iostream.h>
# include <stdio.h>
# include <conio.h>
class st
{
int sno, m1, m2, m3;
char sna[20];
public:
void accept()
{
cout<<"ENTER STUDENT NUMBER:";
cin>>sno;

34
Compiled By Getinet
2010

cout<<"ENTER STUDENT'S NAME:";


cin>>sna;
cout<<"ENTER THE MARKS OF THREE SUBJECTS:";
cin>>m1>>m2>>m3;
}
int get_tot()
{
return(m1+m2+m3);
}
void print()
{
cout<<"STUDENT NUMBER IS:"<<sno<<endl;
cout<<"STUDENT'S NAME IS:"<<sna<<endl;
cout<<"MARKS IN THREE SUBJECTS
ARE:"<<m1<<"\t"<<m2<<"\t"<<m3<<endl;
}
};
void main()
{
st *p,*p1;
int tot,av,n;
clrscr();
cout<<"ENTER NUMBER OF CELLS :";
cin>>n;
p=new st[n];
for(p1=p;(p1-p)<n;p1++)
p1->accept();
clrscr();
cout<<"THE VALUE OF THE ARRAY IS :";
for(p1=p;(p1-p)<n;p1++)
{
tot=p1->get_tot();
av=tot/3;
printf("THE ADDRESS OF CELL IS \n",p1);
cout<<"THE VALUE OF CELL IS :"<<(p1-p)<<endl;
p1->print();
cout<<"TOTAL MARKS ARE :"<<tot<<endl;
cout<<"AVERAGE MARKS ARE :"<<av<<endl;
getch();
}
delete p;
}

TEMPLATES

35
Compiled By Getinet
2010

Templates are the new features added recently to C++. Templates enable us to
define generic classes.
We can define templates for both classes and functions. A template can be used to
create a family of classes or functions. A template can be contributed as a kind of macro.
When an object of a specific type is defined for actual use, the template definition for that
class is substituted with the required datatype. Since a template is defined with a parameter
that would be replaced by the specified datatype at the time of actual use of the class or
function, the templates are some times called parameterized classes or functions.
The class template definition is very similar to an ordinary class definition except
the prefix 'template <class T>' and the use of type T. This prefix tells the compiler that we
are going to declare a template and use T as a type name in the declaration.

Example Program For Template Function.

# include <iostream.h>
# include <conio.h>
template<class A>
A add(A x,A y)
{
return x+y;
}
void main()
{
int m,n;
float f,p;
long l,r;
clrscr();
cout<<"ENTER TWO INTERGER :"<<endl;
cin>>m>>n;
cout<<"ENTER TWO FLOATS :"<<endl;
cin>>f>>p;
cout<<"ENTER TWO LONGS :"<<endl;
cin>>l>>r;
cout<<"FIRST INTEGER IS :"<<m<<endl;
cout<<"SECOND INTEGER IS :"<<n<<endl;
cout<<"FIRST FLOAT IS :"<<f<<endl;
cout<<"SECOND FLOAT IS :"<<p<<endl;
cout<<"FIRST LONG IS :"<<l<<endl;
cout<<"SECOND LONG IS :"<<r<<endl;
cout<<"SUM OF INTEGERS IS :"<<add(m,n)<<endl;
cout<<"SUM OF FLOATS IS :"<<add(f,p)<<endl;
cout<<"SUM OF LONGS IS :"<<add(l,r)<<endl;
getch();
}

36
Compiled By Getinet
2010

Example Program To Template Functions With Multiple Templates.

# include <iostream.h>
# include <stdio.h>
# include <conio.h>
template<class A,class B>
A add (A x,B y)
{
return(x+y);
}
void main()
{
int m;
float f;
long l;
clrscr();
cout<<"ENTER AN INTEGER :"<<endl;
cin>>m;
cout<<"ENTER A FLOAT VALUE :"<<endl;
cin>>f;
cout<<"ENTER A LONG VALUE :"<<endl;
cin>>l;
clrscr();
cout<<"INTEGER VALUE IS :"<<m<<endl;
cout<<"FLOAT VALUE IS :"<<f<<endl;
cout<<"LONG VALUE IS :"<<l<<endl;
cout<<"SUM OF INTEGER AND FLOAT VALUE
IS :"<<add(m,f)<<endl;
cout<<"SUM OF FLOAT AND INTEGER VALUE
IS :"<<add(f,m)<<endl;
cout<<"SUM OF LONG AND FLOAT VALUE
IS :"<<add(l,f)<<endl;
cout<<"SUM OF LONG AND INTEGER VALUE
IS :"<<add(l,m)<<endl;
getch();
}

Example Program For Class Templates.

# include <iostream.h>
# include <conio.h>
template<class A>
class sample

37
Compiled By Getinet
2010

{
A n,m,f;
public:
void input()
{
cout<<"ENTER FIRST VALUE :";
cin>>n;
cout<<"ENTER SECOND VALUE :";
cin>>m;
cout<<"ENTER THIRD VALUE :";
cin>>f;
}
A total()
{
return(n+m+f);
}
void output()
{
cout<<"FIRST VALUE IS :"<<n<<endl;
cout<<"SECOND VALUE IS :"<<m<<endl;
cout<<"THIRD VALUE IS :"<<f<<endl;
}
};
void main()
{
sample <int> T1; //object declared with integer members
sample <float> T2; //object declared with float members
sample <long> T3; //object declared with long members
clrscr();
cout<<"ENTER INTEGER VALUES :"<<endl;
T1.input();
cout<<"ENTER FLOAT VALUES :"<<endl;
T2.input();
cout<<"ENTER LONG VALUES :"<<endl;
T3.input();
clrscr();
cout<<endl<<"INTEGER VALUES ARE :"<<endl;
T1.output();
cout<<"TOTAL VALUE IS :"<<T1.total()<<endl;
cout<<endl<<"FLOAT VALUES ARE :"<<endl;
T2.output();
cout<<"TOTAL VALUE IS :"<<T2.total()<<endl;
cout<<endl<<"LONG VALUES ARE :"<<endl;
T3.output();
cout<<"TOTAL VALUE IS :"<<T3.total()<<endl;
getch();

38
Compiled By Getinet
2010

}
INHERITANCE (REUSABILITY)

1.Single Inheritance:

2.Multi Level Inheritance.

3.MultipleInheritance.

A B

4.Hierarchical Inheritance.

39
B C D
Compiled By Getinet
2010

5.Hybrid Inheritance.

B C

D
Reusability is another important feature of OOP. It is always nice if we could reuse
something that already exists rather than trying to create the same all over again. C++
strongly supports the concept of reusability. The C++ classes can be reused in several
ways. Once a class has been written and tested, it can be adopted by other programmers to
send their requirements. Creating new classes, reusing the properties of the existing ones
basically does this. The mechanism of deriving a new class from an old one is called
"Inheritance" (or derivation). The old class referred to as the base class and the new one
is called derived class.

The derived class inherits some or all the properties of the base class. A class can
also inherits properties from more than one class of from more than one level.

A derived class with only one base class is called single inheritance, and one
derived class with several base classes is called multiple inheritance. On the other hand,
the properties of one class may be inherited by more than one class. This process is known
as hierarchical inheritance. The mechanism of deriving a class from another derived class
is known as multilevel inheritance. The combination of any of two inheritances is called
hybrid inheritance.
Defining a Derived Class.
A derived class is defined by specifying it's relationship with the base class in
addition to it's own details.
Syntax: class derived class_name : visibility_mode base class name
{
- -------
- ------- //members of derived class
- -------
};
The colon(:) indicates that the derived class name is derived from the base class
name. The visibility mode is optional and if present, it may be either private or public. The

40
Compiled By Getinet
2010

default visibility mode is private. This mode specifies whether the features of the base class
are privately derived or publicly derived.
When a base class is privately inherited by a derived class, ‘public members’ of the
base class become ‘private members’ of the derived class and therefore the public members
of the base class can only be accessed by the member functions of the derived class. They
are inaccessible to the objects of the derived class. A public member of a class can be
accessed by its own objects using the dot operator. The result is that no member of the
base class is accessible to the objects of the derived class.
When a base class is publicly inherited by a derived class, public members of the
base class become the pubic members to the derived class and therefore they are accessible
to the objects of the dedrived class.
In both the cases private members are not inherited and therefore the private
members of a base class will never become the members of it's derived class.
E.g.:
class B : public A
{
- - - - -//members of class B
- - - - - -
- - - - - -
- - - - - -
};

Example Program For Single Inheritance.

# include <iostrea
m.h>
# include <conio.h>
class a
{
int x,y;
void input(int p,int r)
{
x=p;
y=r;
}
void print()
{
cout<<"X VALUE IS :"<<x<<endl;
cout<<"Y VALUE IS :"<<y<<endl;
}
class b:public a //deriving a derived class
{
int m,n;
public:
void accept()
{

41
Compiled By Getinet
2010

cout<<"ENTER TWO INTEGERS :";


cin>>m>>n;
}
void display()
{
cout<<"M VALUE IS :"<<m<<endl;
cout<<"N VALUE IS :"<<n<<endl;
}
};
void main()
{
b t; //object declared for class b
clrscr();
t.input(253,445);//member function of base class
t.accept(); //function of the derived class
clrscr();
t.print(); //function of the base class
t.display(); //function of the derived class
getch();
}

Example Program For Multilevel Inheritance Or A Derived Class From Another


Derived Class.

# include <iostream.h>
# include <stdio.h>
# include <string.h>
# include <conio.h>
class student
{
int sno;
char sna[10],sadd[10];
public:
void input()
{
cout<<"ENTER STUDENT NUMBER :";
cin>>sno;
cout<<"ENTER STUDENT'S NAME :";
cin>>sna;
cout<<"ENTER STUDENT'S ADDRESS :";
cin>>sadd;
}
void output()
{
cout<<"STUDENT NUMBER IS "<<sno<<endl;
cout<<"STUENT'S NAME IS "<<sna<<endl;

42
Compiled By Getinet
2010

cout<<"STUDENT'S ADDRESS IS "<<sadd<<endl;


}
};
class fees:public student
{
int tf,fp,due;
char cou[10];
public:
void accept()
{
cout<<"ENTER COURSE NAME :";
cin>>cou;
cout<<"ENTER TOTAL FEE :";
cin>>tf;
cout<<"HOW MUCH FEE IS PAID :";
cin>>fp;
due=tf-fp;
}
void display()
{
cout<<"COURSE NAME IS :"<<cou<<endl;
cout<<"TOTAL FEE IS :"<<tf<<endl;
cout<<"FEE PAID IS :"<<fp<<endl;
cout<<"DUE FEE IS :"<<tf-fp<<endl;
}
};
class marks:public fees
{
int tm,mm,mp,mc,am;
char res[15];
public:
void marksin()
{
cout<<"ENTER MARKS IN MATHS :";
cin>>mm;
cout<<"ENTER MARKS IN PHYSICS :";
cin>>mp;
cout<<"ENTER MARKS IN CHEMISTRY :";
cin>>mc;
}
void resout()
{
tm=mm+mp+mc;
am=tm/3;
if(am>75)
strcpy(res,"DISTINCTION");

43
Compiled By Getinet
2010

else if(am>=60)
strcpy(res,"FIRST CLASS");
else if(am>=50)
strcpy(res,"SECOND CLASS");
else if(am>=35)
strcpy(res,"THIRD CLASS");
else
strcpy(res,"FAILED");
cout<<"MARKS IN MATHS ARE :"<<mm<<endl;
cout<<"MARKS IN PHYSICS ARE :"<<mp<<endl;
cout<<"MARKS IN CHEMISTRY ARE :"<<mc<<endl;
cout<<"TOTAL MARKS ARE :"<<tm<<endl;
cout<<"AVERAGE MARKS ARE :"<<am<<endl;
cout<<"RESULT IS--------------:"<<res<<endl;
}
};

void main()
{
clrscr();
marks obj; //object declaration
obj.input();//member function of class student
obj.accept();//member function of class fees
obj.marksin();//member function of class marks
clrscr();
obj.output(); //member function of class student
obj.display();//member function of class fees
obj.resout();//member function of class marks
getch();
}

MULTIPLE INHERITANCE.
A class can inherit the attributes of two or more classes. This is known as multiple
inheritance. Multiple inheritance allows combining the features of several existing classes
as a starting point for defining a new class.

Syntax: class derived_class : visibility label base class1, visibility label base
class2………
{
- -----------
- -----------
- -----------
- -----------
}
Where visibility label is either public or private. Comma separates the base classes.

44
Compiled By Getinet
2010

PROTECTED MEMBERS.
C++ provides a third visibility modifier protected, which serve a limited purpose in
inheritance. A member declared as protected is accessible by the member functions with in
its class and any class derived from it as the public member of the base class. It cannot be
accessed by the functions outside these classes.
When a protected member is inherited in public mode, it becomes protected in the
derived class too and therefore it is accessible by the member functions of the derived
class. It is also ready for further inheritance.
A protected member is inherited in the private mode derivation, that becomes
private in the derived class. Although it is available to the member functions of the derived
class. It is not available for further inheritance since private members cannot be inherited.

E.g.:
class A
{
protected:
int a;
- - - - - - -
- - - - - - -
- - - - - - -
};
class B : public A
{
- - - - - - //protected members of class A are
- - - - - - //protected to class B
- - - - - -
};
class C : private B
{
- - - - - - //members of class A are
- - - - - - //private to class C
- - - - - -
};
class D : public C
{
- - - - - - //members of class A cannot - - - - - - //be
accessed in class D
- - - - -/ -
};

Example Program For Multiple Inheritance And Protected Members. (Two Or More
Base Classes One Derived Class Is Called Multiple Inheritance).

# include <iostream.h>
# include <conio.h>
class employ

45
Compiled By Getinet
2010

{
protected:
int eno,bs;
char ena[10],eadd[15];
public:
void input()
{
cout<<"ENTER EMPLOY NUMBER :";
cin>>eno;
cout<<"ENTER EMPLOY NAME :";
cin>>ena;
cout<<"ENTER EMPLOY ADDRESS :";
cin>>eadd;
cout<<"ENTER BASIC SALARY :";
cin>>bs;
}
};
class allow
{
protected:
int da,hra,cca;
public:
void accept()
{
cout<<"ENTER DA :";
cin>>da;
cout<<"ENTER HRA :";
cin>>hra;
cout<<"ENTER CCA :";
cin>>cca;
}
};
class ded
{
protected:
int pf,it;
public:
void dedinput()
{
cout<<"ENTER PROVIDENT FUND :";
cin>>pf;
cout<<"ENTER INCOME TAX :";
cin>>it;
}
};
class salary:public employ,public allow,public ded

46
Compiled By Getinet
2010

{
int tall,tded,gs,ns;
public:
void calc_sal()
{
tall=da+hra+cca;
tded=pf+it;
gs=bs+tall;
ns=gs-tded;
}
void output()
{
cout<<"EMPLOY NUMBER IS :"<<eno<<endl;
cout<<"EMPLOY NAME IS :"<<ena<<endl;
cout<<"EMPLOY ADDRESS IS :"<<eadd<<endl;
cout<<"BASIC SALARY IS :"<<bs<<endl;
cout<<"EMPLOY'S DA IS :"<<da<<endl;
cout<<"EMPLOY'S HRA IS :"<<hra<<endl;
cout<<"EMPLOY'S CCA IS :"<<cca<<endl;
cout<<"EMPLOY'S PF IS :"<<pf<<endl;
cout<<"EMPLOY'S IT IS :"<<it<<endl;
cout<<"TOTAL ALLOWANCES :"<<tall<<endl;
cout<<"TOTAL DEDUCTIONS :"<<tded<<endl;
cout<<"EMPLOY'S GROSS SALARY IS :"<<gs<<endl;
cout<<"EMPLOY'S NET SALARY IS :"<<ns<<endl;
}
};
void main()
{
salary s;
s.input();
s.accept();
s.dedinput();
clrscr();
s.calc_sal();
s.output();
getch();
}

HIERARCHICAL INHERITANCE.

In the hierarchical inheritance different classes are derived from one base class. A
subclass can be constructed by inheriting the properties of the base class. A subclass can
serve as a base class for the lower classes and so on.

Example Program For Hierarchical Inheritance.

47
Compiled By Getinet
2010

# include <iostream.h>
# include <conio.h>
# include<string.h>
class student
{
int sno;
char sna[10],sadd[10];
public:
void input()
{
cout<<"ENTER STUDENT'S NUMBER :";
cin>>sno;
cout<<"ENTER STUDENT'S NAME :";
cin>>sna;
cout<<"ENTER STUDET'S ADDRESS :";
cin>>sadd;
}
void output()
{
cout<<"STUDENT'S NUMBER IS :"<<sno<<endl;
cout<<"STUDENT'S NAME IS :"<<sna<<endl;
cout<<"STUDENT'S ADDRESS IS :"<<sadd<<endl;
}
};
class lang
{
int mt,me;
public:
void accept()
{
cout<<"ENTER MARKS IN TELUGU :";
cin>>mt;
cout<<"ENTER MARKS IN ENGLISH :";
cin>>me;
}
void display()
{
cout<<"TELUGU MARKS ARE :"<<mt<<endl;
cout<<"ENGLISH MARKS ARE :"<<me<<endl;
}
};
class mathes:public lang
{
int mm,mp,mc;
public:

48
Compiled By Getinet
2010

void sentry()
{
cout<<"ENTER MARKS IN MATHS :";
cin>>mm;
cout<<"ENTER MARKS IN PHYSICS :";
cin>>mp;
cout<<"ENTER MARKS IN CHEMISTRY:";
cin>>mc;
}
void sprint()
{
cout<<"MARKS IN MATHS ARE :"<<mm<<endl;
cout<<"MARKS IN PHYSICS ARE :"<<mp<<endl;
cout<<"MARKS IN CHEMISTRY ARE :"<<mc<<endl;
cout<<"TOTAL MARKS ARE :"<<mt+me+mm+mp+mc<<endl;
}
};
class computers:public lang
{
int mmt,mph,mcs;
public:
void sentry()
{
cout<<"ENTER MARKS IN MATHS :";
cin>>mmt;
cout<<"ENTER MARKS IN PHYSICS :";
cin>>mph;
cout<<"ENTER MARKS IN COMPUTERS:";
cin>>mcs;
}
void sprint()
{
cout<<"MARKS IN MATHS ARE :"<<mmt<<endl;
cout<<"MARKS IN PHYSICS ARE :"<<mph<<endl;
cout<<"MARKS IN COMPTERS ARE :"<<mcs<<endl;
cout<<"TOTAL MARKS ARE
:"<<mt+me+mmt+mph+mcs<<endl;
}
};
class arts:public lang
{
int mhs,mec,mci;
public:
void sentry()
{
cout<<"ENTER MARKS IN HISTORY :";

49
Compiled By Getinet
2010

cin>>mhs;
cout<<"ENTER MARKS IN ECONOMICS:";
cin>>mec;
cout<<"ENTER MARKS IN CIVICS :";
cin>>mci;
}
void sprint()
{
cout<<"HISTORY MARKS ARE :"<<mhs<<endl;
cout<<"ECONOMICS MARKS ARE :"<<mec<<endl;
cout<<"CIVICS MARKS ARE :"<<mci<<endl;
cout<<"TOTAL MARKS ARE :"<<mt+me+mhs+mec+mci<<endl;
}
};
void main()
{
mathes m;
computers cs;
arts a;
clrscr();
m.accept();
m.sentry();
clrscr();
cs.accept();
cs.sentry();
clrscr();
a.accept();
a.sentry();
clrscr();
m.display();
m.sprint();
getch();
cs.display();
cs.sprint();
getch();
a.display();
a.sprint();
getch();
}

Example For Hybrid Example. (The Combination Of Any Two Inheritance Is Called
Hybrid Inheritance.

# include <iostream.h>
# include <stdio.h>
# include <conio.h>

50
Compiled By Getinet
2010

# include <string.h>
class student
{
protected:
int sno;
char sna[20],sadd[25];
public:
void input()
{
cout<<"ENTER STUENT NUMBER :";
cin>>sno;
cout<<"ENTER STUDENT'S NAME :";
cin>>sna;
cout<<"ENTER STUDENT'S ADDRESS:";
cin>>sadd;
}
};
class test:public student
{
protected:
int mm,mp,mc;
public:
void mentry()
{
cout<<"ENTER MARKS IN MATHS :";
cin>>mm;
cout<<"ENTER MARKS IN PHYSICS :";
cin>>mp;
cout<<"ENTER MARKS IN CHEMISTRY:";
cin>>mc;
}
};
class sports
{
protected:
int sm;
public:
void sentry()
{
cout<<"ENTER SPORTS MARKS :";
cin>>sm;
}
};
class result:public test, public sports
{
int tot,avg;

51
Compiled By Getinet
2010

char res[20];
public:
void findres()
{
tot=mm+mp+mc;
avg=tot/3;
if(sm>50)
avg=avg+5;
if(avg>=75)
strcpy(res,"DISTINCTION");
else if(avg>=60)
strcpy(res,"FIRST CLASS");
else if(avg>=50)
strcpy(res,"SECOND CLASS");
else if(avg>=35)
strcpy(res,"THIRD CLASS");
else if(avg<35)
strcpy(res,"FAILED");
}
void display()
{
cout<<"STUDENT NUMBER IS :"<<sno<<endl;
cout<<"STUDENT'S NAME IS :"<<sna<<endl;
cout<<"STUDENT'S ADDRESS IS :"<<sadd<<endl;
cout<<"MARKS IN MATHS ARE :"<<mm<<endl;
cout<<"MARKS IN PHYSICS ARE :"<<mp<<endl;
cout<<"MARKS IN CHEMISTRY ARE:"<<mc<<endl;
cout<<"TOTAL MARKS ARE :"<<tot<<endl;
cout<<"AVERAGE MARKS ARE :"<<avg<<endl;
cout<<"RESULT OBTAINED :"<<res<<endl;
}
};
void main()
{
result r;
clrscr();
r.input(); //member function of student class
r.mentry(); //member function of test class
r.sentry(); //member function of sports class
r.findres(); //member function of result class
clrscr();
r.display();
getch();
}

52
Compiled By Getinet
2010

Virtual Base class

Grant parent

Parent1 Parent2

Child
Consider a situation where all the three kinds of inheritances, namely multilevel, multiple,
and hierarchical inheritance, are involved. This is illustrated in the above figure. The child
has two direct base classes parent1 and parent2 which themselves have a common base
class ‘grand parent’. The child inherits the traits of ‘grandparent’ via two separate paths. It
can also inherit directly as shown by the broken line. The ‘grandparent is sometimes
referred to as indirect base class.
Inheritance by the child as shown in the figure might pose some problems. All the
public and protected members of ‘grandparent’ are inherited into child twice, first via
‘parent1’ and again via ‘parent2’. This means, ‘child’ would have duplicate sets of the
members inherited from ‘grand parent’. This introduces ambiguity and should be avoided.
The duplication of inherited memebrs due to these multiple paths can be avoided by
making the common base class as virtual base class while declaring the direct or
intermediate base classes which is shown as follows.

Class A
{
-----
};
class b1 : virtual public A
{
-------
};

53
Compiled By Getinet
2010

class b2 : public virtual A


{
------
};
class C : public b1, public b2
{
---- //only one copy of A will be inherited
};

VIRTUAL FUNCTIONS

Polymorphism refers to the property by which objects be


longing to different classes are able to respond to the same message, but in different forms.
An essential requirement of polymorphism is therefore the ability to refer to objects
without any regard to their classes. This necessitates the use of a single pointer variable to
refer to the objects of different classes. Here, we use the pointer to base class to refer to all
the derived objects. But, we just discovered that a base pointer, even when it is made to
contain the address of a derived class, always executes the function in the base class. The
compiler simply ignores the contents of the pointer and chooses the member functions that
matches the type of the pointer. How do we then achieve polymorphism? It is achieved
using what is known as ‘virtual’ functions.
When we use the same function name in both the base and derived classes, the
function in base class is declared as virtual using the keyword virtual preceding its normal
declaration. When a function is made virtual, C++ determines which function to use at run
time based on the type of object pointed to by the base pointer, rather than the type of the
pointer. Thus by making the base pointer to point to different objects, we can execute
different versions of the virtual function.

INLINE FUNCTIONS

One of the objectives of using functions in a program is to save some memory


space, which becomes appreciable when a function is likely to be called many times.
However, every time a function is called, it takes a lot of extra time in executing a series of
instructions for tasks such as jumping to the function, saving registers, pushing arguments
into the stack, and returning to the calling function. When a function is small, a
substantitial percentage of exectution time may be spent in such over heads.
One solution to this problem is to use macro definitions, popularly known as
macros. Preprocessor macros are popular in C. The major drawback with macros is that
they are not really functions and therefore, the usual error checking does not occur during
compilation.
C++ has a different solution to this problem. To eliminate the cost of calls to small
functions, C++ proposes a new feature called inline function. An inline function is a

54
Compiled By Getinet
2010

function that is expanded inline when it is invoked. That is, the compiler replaces the
functions call with the corresponding function code. The inline functions are defined as
follows.
inline function_header
{
function body
}

FILE HANDLING IN C++

File is a collection of related data stored in a particular area on the disk. Data is
stored on floppy of hard disks using the concept of files. Programs can be designed to
perform the read and write operations in these files. A program typically includes either or
both of the following kinds

1.Data transfer between the console unit and the program (reading).
2.Data transfer between the program and a disk file (write).
The input and output system of C++ handles file operations which are very much
similar to the console input and output operation. It uses file streams as an interface
between the program and files. The system that supplies data to the program is known as
input stream and one that receives data from the program is known as output stream.

The input and output system of C++ contains a set of class that define the file
handling methods. These include the following:

1.ofstream:- It provides output operations. It contains open(), with default output mode
(write mode). It inherits put(), seekp(), tellp(), write() functions.

2.ifstream: - It provides input operations. It contains open(), with default input mode. It
inherits the function get(), getline(), read(), seekg(), tellg() functions.

3.fstream: - It provides support for simultaneous input and output operations. It contains
open with default input mode.

Opening a File:
To open a file you must first create a file stream and then link it to the file name. A
file stream can be defined using the above classes contained in the header file <fstream.h>.
The classes to be used depend upon the purpose, whether you want to read data from the
file or write data to it. A file can be opened in two ways
1. Using the constructor function of the class.
2. Using the member functions open() of the class.
1.To Constructor:
Syntax: file_stream_class stream object("file name")
E.g.: ofstream fp("stud.dat"); //open stud.dat file in output mode
ifstream fp1("sales.dat"); //open sales.dat file in input mode

55
Compiled By Getinet
2010

2.Using open Function.


Syntax: file_steam_class stream_object;
Stream_object.open("file name");
E.g.: ofstream fp;
fp.open("dealer.dat"); //opens dealer.dat in output mode
ifstream fp2;
fp2.open("student.dat"); //opens student.dat file in input mode

ifstream fp3;
fp3.open("marks.dat"); //opens marks.dat file in input mode

Note: Use the first syntax to open a single file in the stream object. Use the second syntax
to open multiple files in the stream object.
write() and read() functions.
The funct ions write () and read () are used to store the values in the disk file in
the same format in which they are stored in the internal memory.
Syntax: stream_object.write ((char *)&v,sizeof(v));
stream_object.read((char *)&v,sizeof(v));
These two functions are used to write and read data. These functions take two
arguments.
The first is the address of the variable V and the second is the length of that variable
must be cast to type char * that is pointer to character type.
close Function.
Closes the currently opened file or files.
Syntax: stream_object.close();
fp.close();
fp1.close();
eof() Function.
This function returns true(1) if end of file is encountered while reading, otherwise it
returns the false (0).
Syntax: stream_object.eof();
fp.eof();

Create A Data File With The Structure Student Number, Name And Total Marks
And Write A Program To Accept Records In That File.
(Data Creation For Student Record Example).

(Flwristu.cpp)

# include <iostream.h>
# include <conio.h>
# include <fstream.h>
class stud
{
int sno,tm;

56
Compiled By Getinet
2010

char sna[20];
public:
void input()
{
cout<<"ENTER STUDENT NUMBER ";
cin>>sno;
cout<<"ENTER STUDENT NAME ";
cin>>sna;
cout<<"ENTER TOTAL MARKS ";
cin>>tm;
}
};
void main()
{
ofstream fp("student.dat");
stud s;
char ch='y';
while(ch=='y' || ch=='Y')
{
clrscr();
s.input();
fp.write((char *)&s,sizeof(s));
cout<<"DO YOU WANT TO ENTER ONE MORE RECORD Y/N ";
cin>>ch;
}
fp.close();
}

Data Processing Program For Above Student Record.


flrdstu.cpp
# include <iostream.h>
# include <conio.h>
# include <fstream.h>
class stud
{
int sno,tm;
char sna[20];
public:
void output()
{
cout<<"STUDENT NUMBER IS "<<sno<<endl;
cout<<"STUDENT NAME IS "<<sna<<endl;
cout<<"STUDENT TOTAL MARKS "<<tm<<endl;
}
};
void main()

57
Compiled By Getinet
2010

{
ifstream fp("student.dat");
stud s;
clrscr();
fp.read((char *)&s,sizeof(s));
while(!fp.eof())
{
s.output();
fp.read((char *)&s,sizeof(s));
getch();
}
fp.close();
}

Create A Data File Employ.Dat With The Structure Employ Number, Name, Employ
Grade (A/B/C) And Basic Salary And Write A Program To Write The Records Into That
File.
(Data Creation Into The Employ.Dat File).

# include <iostream.h>
# include <conio.h>
# include <fstream.h>
class empl
{
int eno,bs;
char eg,ena[20];
public:
void input()
{
cout<<"ENTER EMPLOY NUMBER ";
cin>>eno;
cout<<"ENTER EMPLOY NAME ";
cin>>ena;
cout<<"ENTER EMPLOY GRADE A/B/C ";
cin>>eg;
cout<<"ENTER BASIC SALARY ";
cin>>bs;
}
};
void main()
{
char ch='y';
empl e;
ofstream fp("employ.dat");
while(ch=='y' || ch=='Y')
{

58
Compiled By Getinet
2010

clrscr();
e.input();
fp.write((char *)&e,sizeof(e));
cout<<"DO YOU WANT TO ENTER ONE MORE RECORD Y/N ";
cin>>ch;
}
fp.close();
}

Process The Data File Employ.Data And Calculate The Da, Hra, Pf, It, Gross Salary And
Net Salary According To The Following Conditions.

Grade da Hra Pf It
A 20 25 12 10
B 16 21 9 6
C 12 16 6 4

FLEMPRD.CPP
//Data Processing Program For Above Employ.Dat Record).

# include <iostream.h>
# include <conio.h>
# include <fstream.h>
class empl
{
int eno,bs;
char eg,ena[20];
public:
void output()
{
int da,hra,pf,it,gs,ns;
if(eg=='a' || eg=='A')
{
da=bs*0.2;
hra=bs*0.25;
pf=bs*0.12;
it=bs*0.1;
}
else if(eg=='b' || eg=='B')
{
da=bs*0.16;
hra=bs*0.21;
pf=bs*0.09;
it=bs*0.06;
}
else if(eg=='c' || eg=='C')

59
Compiled By Getinet
2010

{
da=bs*0.12;
hra=bs*0.16;
pf=bs*0.06;
it=bs*0.04;
}
gs=bs+da+hra;
ns=gs-(pf+it);
cout<<"EMPLOY NUMBER "<<eno<<endl;
cout<<"EMPLOY NAME "<<ena<<endl;
cout<<"EMPLOY GRADE "<<eg<<endl;
cout<<"BASIC SALARY "<<bs<<endl;
cout<<"DAILY ALLOWANCE "<<da<<endl;
cout<<"HRA IS "<<hra<<endl;
cout<<"PROVIDENT FUND "<<pf<<endl;
cout<<"INCOME TAX "<<it<<endl;
cout<<"GROSS SALARY "<<gs<<endl;
cout<<"NET SALARY "<<ns<<endl;
}
};
void main()
{
empl e;
ifstream fp;
fp.open("employ.dat");
fp.read((char *)&e,sizeof(e));
clrscr();
while(!fp.eof())
{
e.output();
cout<<endl;
getch();
fp.read((char *)&e,sizeof(e));
}
fp.close();
}

FILE OPENING MODES IN C++.

You can use ifstream and ofstream constructors and the function open() to create
new files as well as to open the existing files. In both these methods, we used only one
argument that was the filename however these functions can take two arguments, the
second one for specifying the file mode. The general form of the function open () with two
arguments is

Stream_object.open("filename", mode);

60
Compiled By Getinet
2010

The second argument mode specifies the purpose for which the file is opened. The
prototype of these class member functions contains default values for the second arguments
and therefore they use the actual values. The default values are as follows.

ios::in for ifstream functions meaning open for reading only.


ios::out for ofstream functions meaning open for writing only.

The file mode parameter can take one of such constants defined in the class "ios".

Parameter Meaning

ios::app Append to end of file.


ios::ate Go to end of file at opening.
ios::binary Binary file.
ios::in Open file for read only.
ios::nocreate Open fails if the file not exists.
ios::noreplace Open fails if the read only exists.
ios::out Open file for writing only.
ios::trunc Delete contents of the file if it exists.

1. Opening a file in ios::out mode also opens it in the ios::trunc mode by default.

2. Both ios::app and ios::ate take us to the end of file when it is opened. But the difference
between the two parameters is that the ios::app allows us to add data to the end of file only.
While ios::ate mode permits us to add data or to modify the existing data any where in the
file. In both the cases a file created by the specified name, if it does not exist.

3. The mode can combine two or more parameters using the "|" symbol.

E.g.: fstream fp;


fp.open("sales.dat",ios::app); //opens sales.dat in append mode
fstream fp1;
//if the file exists opens x.dat in append mode else no creation of file
fp1.open("x.dat",ios::app | ios::nocreate);
//opens file in read and write mode
fp2.open("student.dat",ios::in | ios::out);
fstream fp3;
//opens the file append and read mode
fp3.open("dealer.dat",ios::app | ios::in);

ERROR HANDLING DURING FILE OPERATIONS.


One of the following things may be happened when dealing with files.

1. A file, which you are attempting to open for reading, does not existing.

61
Compiled By Getinet
2010

2. The file name used for a new file may already exist.
3. You may attempt individual operations such a reading past the end of the file.
4. There may not be any space in the disk for storing more data.
5. You may use any invalid file name.
6. You may attempt to perform an operation when the file is not opened for that purpose.

In C++, file streams inherits a stream static member from the class ios. This member
records information of the status of the file that is being currently used. The stream state
member uses bit fields to store the status of the error conditions stated above.
The class ios supports several member functions that can be used to read the status
recorded in a file stream.
____ __________
Functions Return Value and Meaning __
eof( ) Returns true (non-zero value) if end of file is
encountered while reading, otherwise returns false
(zero).

fail( ) Returns true when an input or output operation is fail


otherwise false.

bad( ) Returns true if an invalid operation is attempted of


any unrecoverable error has occurred. However it is
false it may be possible in recover from any other
error reported and continue operation.

good( ) Returns true if no error has occurred. This means all


the above functions are false. When it returns false no
function operation can be carried out.

Data Creation For Bank.Dat File.


flbnkwri.cpp
//adding new records to the file
# include <iostream.h>
# include <conio.h>
# include <fstream.h>
# include <process.h>
class bank
{
int acno;
char acname[20];
float cbal;
public:
void input()
{
cout<<"ENTER ACCOUNT NUMBER ";

62
Compiled By Getinet
2010

cin>>acno;
cout<<"ENTER NAME OF THE PERSON ";
cin>>acname;
cout<<"ENTER CURRENT BALANCE ";
cin>>cbal;
}
};
void main()
{
fstream fp;
bank a;
fp.open("bank.dat",ios::app);
if(fp.fail())
{
cout<<"UNABLE TO OPEN FILE";
exit(0);
}
char ch='y';
while(ch=='y' || ch=='Y')
{
a.input();
fp.write((char *)&a,sizeof(a));
if(fp.fail())
{
cout<<"CANNOT WRITE TO THE FILE "<<endl;
exit(0);
}
cout<<"DO YOU WANT TO ENTER MORE REOCORDS Y/N ";
cin>>ch;
}
fp.close();
}

Data Processing Program For Above Bank.Dat File Program.

//DATA PROCESSING PROGRAM


# include <iostream.h>
# include <conio.h>
# include <fstream.h>
# include <process.h>
class bank
{
int acno;
char acname[20];
float cbal;
public:

63
Compiled By Getinet
2010

void output()
{
cout<<"ACCOUNT NO IS "<<acno<<endl;
cout<<"ACCOUNT HOLDER NAME "<<acname<<endl;
cout<<"CURRENT BALANCE "<<cbal<<endl;
}
};
void main()
{
bank a;
fstream fp;
fp.open("bank.dat",ios::in);
if(!fp.good())
{
cout<<"FILE NOT FOUND ";
getch();
exit(0);
}
fp.read((char *)&a,sizeof(a));
clrscr();
while(!fp.eof())
{
a.output();
fp.read((char *)&a,sizeof(a));
getch();
}
fp.close();
}

Account Number Searching In Sequential Search In Bank.Dat File.

//ACCOUNT NO SEARCHING IN BANK.DAT FILE SEQUENTIAL SEARCH


# include <iostream.h>
# include <conio.h>
# include <fstream.h>
class bank
{
int acno;
char name[20];
float cbal;
public:
void output()
{
cout<<"ACCOUNT HOLDER NUMBER "<<acno<<endl;
cout<<"ACCOUNT HOLDER NAME "<<name<<endl;
cout<<"ACCOUNT HOLDER BALANCE "<<cbal<<endl;

64
Compiled By Getinet
2010

}
int getacno()
{
return acno;
}
};
void main()
{
fstream fp;
bank b;
char ch='y';
fp.open("bank.dat",ios::in);
int tacno;
clrscr();
while(ch=='y' || ch=='Y')
{
cout<<"ENTER ACCOUNT HOLDER NUMBER TO FIND ";
cin>>tacno;
fp.read((char *)&b,sizeof(b));
while(tacno!=b.getacno() && !fp.eof())
fp.read((char *)&b,sizeof(b));
if(!fp.eof())
b.output();
else
cout<<"YOUR ACCOUNT NO NOT FOUND "<<endl;
cout<<"DO YOU WANT TO SEE ONE MORE RECORD Y/N ";
cin>>ch;
}
fp.close();
}

RANDOM ACCESSING FILE FUNCTIONS.

By using seekg( ) and seekp( ) functions, you can access the records randomly.

Syntax: seekg(offset, ref_position);


seekp(offset, ref_position);

seekg moves getpointer(input) to a


specified location.

seekp moves put pointer(output) to a


specified location.

The parameter "offset" represents the no. of bytes the file pointer is to be moved
from the location specified by the parameter "ref_position".

65
Compiled By Getinet
2010

Ref-Position:
Takes one of the following three constructors defined in the ios classes.
ios::beg beginning of the file.
ios::cur current position of the pointer.
ios::end end of the file.

The seekg() function moves the associated files get pointer while the seekp()
function moves the associated files put pointer.

Seek call Action

seekg(0, ios::beg); Go to the beginning of the file.


seekg(0, ios::cur); Stay at the current position.
seekg(0, ios::end); Go to the end of the file.
seekg(m, ios::beg); moves to (m+1)th byte in the file.
seekg(m, ios::cur); Go forward by m bytes from the current position.
seekg(-m, ios::cur); Go backward by m bytes from the current position.
seekg(-m, ios::end); Go backward by m bytes from the end.

Note: You can also use seekp() in the same syntax to move put pointer. You can
also use tellg() and tellp() functions to return the number of bytes from the beginning of
the pointer position.

Syntax: stream_object.tellp();
stream_object.tellg();

Program For Record Number Searching In A Data File.


//RECORD NUMBER SEARCHING IN BANK FILE IN RANDOM ORDER
# include <iostream.h>
# include <conio.h>
# include <fstream.h>
class bank
{
int acno;
char acna[20];
float cbal;
public:
void output()
{
cout<<"ACCOUNT HOLDER NUMBER "<<acno<<endl;
cout<<"ACCOUNT HOLDER NAME "<<acna<<endl;
cout<<"CURRENT BALANCE "<<cbal<<endl;
}
};
void main()
{

66
Compiled By Getinet
2010

fstream fp;
bank b;
int rno,nor;
fp.open("bank.dat",ios::in);
fp.seekg(0,ios::end);
nor=fp.tellg() /sizeof(b);
fp.close();
clrscr();
char ch='y';
while(ch=='y' || ch=='Y')
{
cout<<"ENTER RECORD NO YOU WANT TO SEE <<nor;
cin>>rno;
if(rno<=nor)
{
fp.open("bank.dat",ios::in);
fp.seekg((rno-1)*sizeof(b),ios::beg);
fp.read((char *)&b,sizeof(b));
b.output();
fp.close();
}
else
cout<<"RECORD NO NOT IN THE RANGE "<<endl;
getch();
cout<<"DO YOU WANT TO SEE ONE MORE RECORD Y/N ";
cin>>ch;
}
}

Menu Program For Processing Employ.Dat File.

//MENU PROGRAM FILE FOR PROCESSING EMPLOY.DAT FILE


# include <iostream.h>
# include <conio.h>
# include <stdio.h>
# include <string.h>
# include <fstream.h>
class employ
{
int eno,bsal;
char ena[20];
public:
void puteno(int x)

67
Compiled By Getinet
2010

{
eno=x;
}
void input()
{
cout<<"ENTER EMPLOY NAME ";
cin>>ena;
cout<<"ENTER BASIC SALARY ";
cin>>bsal;
}
void output()
{
cout<<"EMPLOY NUMBER IS "<<eno<<endl;
cout<<"EMPLOY NAME IS "<<ena<<endl;
cout<<"EMPLOY'S BASIC SALARY IS "<<bsal<<endl;
}
void display()
{
cout<<eno<<"\t\t"<<ena<<"\t\t"<<bsal<<endl;
}
int geteno()
{
return(eno);
}
};
void main()
{
int op=1,teno;
employ e;
fstream fp,fp1;
while(op<5)
{
clrscr();
cout<<"\t"<<"1.NEW EMPLOY"<<endl;
cout<<"\t"<<"2.DELETION"<<endl;
cout<<"\t"<<"3.UPDATION"<<endl;
cout<<"\t"<<"4.LIST"<<endl;
cout<<"\t"<<"5.EXIT"<<endl;
cout<<"ENTER YOUR CHOICE ";
cin>>op;
switch(op)
{
case 1:
clrscr();
fp.open("employ.dat",ios::in);
if(fp.good())

68
Compiled By Getinet
2010

{
fp.read((char *)&e,sizeof(e));
while(!fp.eof())
{
teno=e.geteno();
fp.read((char *)&e,sizeof(e));
}
teno++;
}
else
teno=100;
fp.close();
e.puteno(teno);
cout<<"EMPLOY NUMBER IS "<<teno<<endl;
e.input();
fp.open("employ.dat",ios::app);
fp.write((char *)&e,sizeof(e));
fp.close();
break;

case 2:
clrscr();
fp.open("employ.dat",ios::in);
if(fp.bad())
{
cout<<"FILE NOT FOUND"<<endl;
getch();
fp.close();
}
else
{
cout<<"ENTER EMPLOY NUMBER TO DELETE ";
cin>>teno;
fp1.open("temp.dat",ios::out);
fp.read((char *)&e,sizeof(e));
int s=0;
while(!fp.eof())
{
if(teno != e.geteno())
fp1.write((char *)&e,sizeof(e));
else
s++;
fp.read((char *)&e,sizeof(e));
}
fp.close();
fp1.close();

69
Compiled By Getinet
2010

remove("employ.dat");
rename("temp.dat","employ.dat");
if(s>0)
cout<<"RECORD DELETED SUCCESSFULLY "<<teno<<endl;
else
cout<<"RECORD NOT FOUND "<<teno<<endl;
}
getch();
break;
case 3:
clrscr();
fp.open("employ.dat",ios::in | ios::out);
if(fp.bad())
{
cout<<"FILE NOT FOUND "<<endl;
getch();
fp.close();
}
else
{
cout<<"ENTER EMPLOY NO TO MODIFY ";
cin>>teno;
fp.read((char *)&e,sizeof(e));
int i=0;
while(teno!=e.geteno() && !fp.eof())
{
i++;
fp.read((char *)&e,sizeof(e));
}
if(!fp.eof())
{
clrscr();
cout<<"RECORD BEFORE UPDATION "<<endl;
e.output();
cout<<"ENTER NEW DETAILS "<<endl;
e.input();
fp.seekp((i*sizeof(e)),ios::beg);
fp.write((char *)&e,sizeof(e));
cout<<"RECORD AFTER UPDATION "<<endl;
e.output();
}
else
cout<<"EMPLOYEE NO NOT FOUND WITH THE NUMBER
"<<teno<<endl;
fp.close();
}

70
Compiled By Getinet
2010

getch();
break;

case 4:
int ch=0;
while(ch<3)
{
clrscr();
cout<<"\t"<<"1.INDIVIDUAL "<<endl;
cout<<"\t"<<"2.LIST OF EMPLOYEE "<<endl;
cout<<"\t"<<"3.RETURN TO MAIN "<<endl;
cout<<"ENTER YOUR OPTION ";
cin>>ch;
switch(ch)
{
case 1:
fp.open("employ.dat",ios::in);
if(fp.bad())
{
cout<<"FILE NOT FOUND ";
getch();
fp.close();
}
else
{
cout<<"ENTER EMPLOY NUMBER ";
cin>>teno;
fp.read((char *)&e,sizeof(e));
while(teno!=e.geteno() && !fp.eof())
fp.read((char *)&e,sizeof(e));
if(!fp.eof())
{
clrscr();
e.output();
}
else
cout<<"EMPLOYEE NO NOT FOUND "<<teno<<endl;
getch();
fp.close();
}
break;
case 2:
clrscr();
fp.open("employ.dat",ios::in);
if(fp.bad())
{

71
Compiled By Getinet
2010

cout<<"FILE NOT FOUND "<<endl;


getch();
fp.close();
}
else
{
cout<<"\t\t"<<"EMPLOY LIST"<<endl;

cout<<"ENO"<<"\t\t"<<"EMAME"<<"\t\t"<<"BASIC"<<endl;
fp.read((char *)&e,sizeof(e));
while(!fp.eof())
{
e.display();
fp.read((char *)&e,sizeof(e));
}
fp.close();
getch();
}
break;
} //SWITCH END
} //WHILE END
} //SWITCH END
} //WHILE END
} //MAIN END

The Bank Of India Is Giving Pay Slips For Their Employees. They Are Maintaining
Different Files For Their Payroll System. They Are Employ.Dat, Salary.Dat And Loan.Dat.
These 3 Files Have Data. The Employ.Dat File Contains All Employees Information
Including Designation And The Salary.Dat File Contains Basic Pay And Rates Of Da, Hra,
Pf And It. The Loan.Dat File Contains Employees Loan Information. The File Structures
Are As Follows:

Employ.Dat Salary.Dat Loan.Dat


Emp-No Int Desg Char Eno Int
Emp-Name Char[10] Bs Float Ldesc Char[20]
Emp-Addr Char[10] Da Float Amt Float
Desg Char[10] Hra Float Noi Int
Jd Char[10] Pf Float Ri Int
It Float
Prepare The Pay Slips For Each And Every Employee In The Following Format.

BANK OF INDIA
HYDERABAD
PAY SLIP FOR THE MONTH OF:

72
Compiled By Getinet
2010

EMPLOY NUMBER: EMPLOY NAME:


EMPLOY ADDRESS:
EMPLOY DESIGNATION:

BASIC SALARY DA HRA PF IT

LOAN AMOUNT

TOTAL ALLOWANCES:

TOTAL DEDUCTIONS:

GROSS SALARY:

NET SALARY:

1. If Loan Is There In Loan.Dat, Calculate The Loan Amount As Per The Following
Formula
Loan Amount = Amt Taken /No Of Installments

2. If There Is No Loan Then Loan Amount =0.


3. After Creating Pay Slip If Any Loan Is There Decrease One From The Remaining
Installments.

FLBNKLNW.CPP
//DATA CREATION FOR EMP.DAT, SALARY.DAT AND LOAN.DAT
# include <iostream.h>
# include <conio.h>
# include <fstream.h>
class employ
{
int eno;
char ena[10],eadd[10],desg[10],jd[10];
public:
void input()
{
cout<<"ENTER EMPLOY NO ";
cin>>eno;
cout<<"ENTER EMPLOY NAME ";
cin>>ena;
cout<<"ENTER EMPLOY ADDRESS ";

73
Compiled By Getinet
2010

cin>>eadd;
cout<<"ENTER EMPLOY DESIGNATION";
cin>>desg;
cout<<"ENTER EMPLOYE JOINDATE ";
cin>>jd;
}
};
class salary
{
char desg[10];
float bs,hra,da,pf,it;
public:
void accept()
{
cout<<"ENTER DESIGNATION ";
cin>>desg;
cout<<"ENTER BASIC ";
cin>>bs;
cout<<"ENTER HRA ";
cin>>hra;
cout<<"ENTER DA ";
cin>>da;
cout<<"ENTER PF ";
cin>>pf;
cout<<"ENTER IT ";
cin>>it;
}
};
class loan
{
int eno,amt,noi,ri;
char ldesc[10];
public:
void linput()
{
cout<<"ENTER EMPLOY NUMBER ";
cin>>eno;
cout<<"ENTER LOAN DESCREPTION ";
cin>>ldesc;
cout<<"ENTER AMOUNT ";
cin>>amt;
cout<<"ENTER NO. INSTALMENTS ";
cin>>noi;
cout<<"ENTER REMAINING INSTLM ";
cin>>ri;
}

74
Compiled By Getinet
2010

};
void main()
{
employ emp;
salary sal;
loan l;
ofstream fp;
fp.open("emp.dat");
char ch='y';
while(ch=='y' || ch=='Y')
{
clrscr();
emp.input();
fp.write((char *)&emp,sizeof(emp));
cout<<"DO YOU WANT TO ENTER MORE RECORDS Y/N ";
cin>>ch;
}
fp.close();
fp.open("salary.dat");
ch='y';
while(ch=='y' || ch=='Y')
{
clrscr();
sal.accept();
fp.write((char *)&sal,sizeof(sal));
cout<<"DO YOU WANT TO ENTER MORE RECORDS Y/N ";
cin>>ch;
}
fp.close();
fp.open("loan.dat");
ch='y';
while(ch=='y' || ch=='Y')
{
clrscr();
l.linput();
fp.write((char *)&l,sizeof(l));
cout<<"DO YOU WANT TO ENTER MORE RECORDS Y/N ";
cin>>ch;
}
fp.close();
}

Program For Data Processing For Creating Pay Slips For Employ.Dat, Salary.Dat And
Loan.Dat.
//DATA PROCESSING FOR CREATING PAY SLIPS
# include <iostream.h>

75
Compiled By Getinet
2010

# include <conio.h>
# include <string.h>
# include <dos.h>
# include <stdio.h>
# include <fstream.h>
class salary;
class employ
{
int eno;
char ena[10],eadd[10],desg[10],jd[10];
public:
void output()
{
gotoxy(5,8);
cout<<"EMPLOY NUMBER:"<<eno;
gotoxy(35,8);
cout<<"EMPLOY NAME:"<<ena;
gotoxy(5,9);
cout<<"DESIGNATION:"<<desg;
gotoxy(35,9);
cout<<"EMPLOY ADDRESS:"<<eadd;
}
int geteno()
{
return eno;
}
friend int chkdesg(employ e,salary s);
};
class salary
{
char desg[10];
float bs,hra,da,pf,it;
public:
int getbs() { return bs; }
int getda() { return da; }
int gethra() { return hra; }
int getpf() { return pf; }
int getit() { return it; }
friend int chkdesg(employ e,salary s);
};
class loan
{
int eno,amt,noi,ri;
char ldesc[10];
public:
int loaneno() { return eno; }

76
Compiled By Getinet
2010

int getloan() { return amt/noi; }


int getri() { return ri; }
void decrem() { ri--; }
};
int chkdesg(employ e,salary s) //FRIEND DEFINITION
{
if(stricmp(e.desg,s.desg)==0)
return 1;
else
return 0;
}
void line()
{
for(int i=1;i<=80;i++)
cout<<"-";
}
void main()
{
employ emp;
salary sal;
loan l;
float bs,hra,da,pf,it,gs,ns,tall,tded,lamt;
fstream fp("emp.dat",ios::in);
fstream fp1,fp2;
struct date p;
struct time t;
getdate(&p);
gettime(&t);
fp.read((char *)&emp,sizeof(emp));
while(!fp.eof())
{
fp1.open("salary.dat",ios::in);
fp1.read((char *)&sal,sizeof(sal));
int m=0;
while(!fp1.eof())
{
if(chkdesg(emp,sal)==1)
{
bs=sal.getbs();
da=(bs*sal.getda()/100);
hra=(bs*sal.gethra()/100);
pf=(bs*sal.getpf()/100);
it=(bs*sal.getit()/100);
m++;
break;
}

77
Compiled By Getinet
2010

fp1.read((char *)&sal,sizeof(sal));
}
fp1.close();
if(m==0)
bs=hra=da=pf=it=0;
fp2.open("loan.dat",ios::in | ios::out);
fp2.read((char *)&l,sizeof(l));
int x=0;
while((emp.geteno()!=l.loaneno()) && !fp2.eof())
{
x++;
fp2.read((char *)&l,sizeof(l));
}
if((emp.geteno()==l.loaneno()) && l.getri()>0)
{
lamt=l.getloan();
l.decrem();
fp2.seekp(x*sizeof(l),ios::beg);
fp2.write((char *)&l,sizeof(l));
}
else
lamt=0;
gs=bs+da+hra;
tall=da+hra;
tded=pf+it+lamt;
ns=gs-tded;
clrscr();
gotoxy(1,2);
line();
gotoxy(31,2);
cout<<"STATE BANK OF INDIA";
gotoxy(36,3);
cout<<"PAY SLIPS";
gotoxy(1,4);
line();
gotoxy(10,5);
cout<<"PAY SLIPS FOR THE MONTH OF ";
gotoxy(40,5);
printf("%d",p.da_mon);
gotoxy(5,6);
cout<<"DATE";
gotoxy(15,6);
printf("%d/%d/%d",p.da_day,p.da_mon,p.da_year);
gotoxy(50,6);
cout<<"TIME:";
gotoxy(60,6);

78
Compiled By Getinet
2010

printf("%d:%d:%d",t.ti_hour,t.ti_min,t.ti_sec);
gotoxy(1,7);
line();
gotoxy(1,8);
emp.output();
gotoxy(1,10);
line();
gotoxy(5,11);
cout<<"BASIC \t HRA \t DA \t PF \t IT \t LOAN AMOUNT";
gotoxy(1,12);
line();
gotoxy(5,13);
cout<<bs<<"\t"<<hra<<"\t"<<da<<"\t"<<pf<<"\t"<<it<<"\t"<<lamt
;
gotoxy(1,14);
line();
gotoxy(15,15);
cout<<"TOTAL ALLOWANCES: "<<tall;
gotoxy(15,16);
cout<<"TOTAL DEDUCTIONS: "<<tded;
gotoxy(15,17);
cout<<"GROSS PAY:"<<gs;
gotoxy(15,18);
cout<<"NET PAY:"<<ns;
gotoxy(1,19);
line();
getch();
fp.read((char *)&emp,sizeof(emp));
fp2.close();
}
fp.close();
}
Cput ( ) is the function is to effect the background and foreground colors.

Menu Program For Performing The Arithmetic Operations Like Addition, Subtraction,
Multiplication And Division By Creating A Menu.

//Example program for popup menu operations.


# include <iostream.h>
# include <stdio.h>
# include <string.h>
# include <conio.h>
void box(int sr,int sc,int er,int ec)
{
int i;
gotoxy(sc,sr);

79
Compiled By Getinet
2010

printf("%c",201);
for(i=(sc+1);i<ec;i++)
{
gotoxy(i,sr);
printf("%c",205);
}
gotoxy(ec,sr);
printf("%c",187);
for(i=(sr+1);i<er;i++)
{
gotoxy(ec,i);
printf("%c",186);
}
gotoxy(ec,er);
printf("%c",188);
for(i=(ec-1);i>sc;i--)
{
gotoxy(i,er);
printf("%c",205);
}
gotoxy(sc,er);
printf("%c",200);
for(i=(er-1);i>sr;i--)
{
gotoxy(sc,i);
printf("%c",186);
}
}
int menu()
{
int row,ch,i;
clrscr();
char opt[5][20];
_setcursortype(_NOCURSOR);
strcpy(opt[1],"ADDITION");
strcpy(opt[2],"SUBTRACTION");
strcpy(opt[3],"MULTIPLICATION");
strcpy(opt[4],"EXIT");
row=11;
i=1;
int flag=1;
while(flag)
{
clrscr();
box(9,20,17,50);
gotoxy(25,11);

80
Compiled By Getinet
2010

printf("%s",opt[1]);
gotoxy(25,12);
printf("%s",opt[2]);
gotoxy(25,13);
printf("%s",opt[3]);
gotoxy(25,14);
printf("%s",opt[4]);
textcolor(BLACK);
textbackground(WHITE);
gotoxy(25,row);
cputs(opt[i]);
normvideo();
ch=getch();
switch(ch)
{
case 72: //UPARROW KEY (ASCII CODE) IS 72
row--;
row=row<11?14:row;
break;
case 80: //DOWN ARROW KEY
row++;
row=row>14?11:row;
break;
case 13: //ENTER KEY
flag=0;
}
i=row-10;
}
return(i);
}
void main()
{
int op=0,a,b,c;
op=menu();
_setcursortype(_NORMALCURSOR);
while(op<4)
{
clrscr();
box(8,10,15,70);
gotoxy(15,10);
printf("ENTER FIRST NUMBER :");
scanf("%d",&a);
gotoxy(15,12);
printf("ENTER SECOND NUMBER :");
scanf("%d",&b);
clrscr();

81
Compiled By Getinet
2010

box(8,10,16,70);
gotoxy(15,10);
printf("FIRST NUMBER IS %d",a);
gotoxy(15,12);
printf("SECOND NUMBER IS %d",b);
switch(op)
{
case 1:
c=a+b;
gotoxy(15,14);
printf("ADDITION IS %d",c);
getch();
break;
case 2:
c=a-b;
gotoxy(15,14);
printf("SUBTRACTION IS %d",c);
getch();
break;
case 3:
c=a*b;
gotoxy(15,14);
printf("MULTIPLICATION IS %d",c);
getch();
break;
}
op=menu();
}
}

Create A Data File Bank.Dat With The Structure Account Holder Number, Name,
Balance And Design A Popup Menu Program In Following.
New Account
Transactions
Cancellations
Listing
Individual
Listing
Return to Main
MY.H PROGRAM

//POPUP MENU PROGRAM FOR PROCESSING BANK.DAT FILE


//USER DEFINED HEADER FILE
# include <iostream.h>
# include <conio.h>
# include <fstream.h>

82
Compiled By Getinet
2010

# include <string.h>
# include <stdio.h>
int r; //GLOBAL VARIABLE
void box(int sr=1,int sc=1,int er=24,int ec=75)
{
int a,i;
gotoxy(sc,sr);
printf("%c",201);
for(i=(sc+1);i<ec;i++)
{
gotoxy(i,sr);
printf("%c",205);
}
gotoxy(ec,er);
printf("%c",187);
for(i=(sc+1);i<er;i++)
{
gotoxy(ec,i);
printf("%c",186);
}
gotoxy(ec,er);
printf("%c",188);
for(i=(ec-1);i>sc;i--)
{
gotoxy(i,er);
printf("%c",205);
}
gotoxy(sc,er);
printf("%c",200);
for(i=(er-1);i>sr;i--)
{
gotoxy(sc,i);
printf("%c",186);
}
}
int menu()
{
int row,ch,i;
clrscr();
char opt[6][20];
strcpy(opt[1],"NEW ACCOUNT");
strcpy(opt[2],"TRANCTIONS");
strcpy(opt[3],"CANCELLATION");
strcpy(opt[4],"LISTING");
strcpy(opt[5],"EXIT");
row=1;

83
Compiled By Getinet
2010

i=1;
int flag=1;
while(flag)
{
clrscr();
box(9,15,17,40);
gotoxy(15,11);
printf("%s",opt[1]);
gotoxy(15,12);
printf("%s",opt[2]);
gotoxy(15,13);
printf("%s",opt[3]);
gotoxy(15,14);
printf("%s",opt[4]);
gotoxy(15,15);
printf("%s",opt[5]);
textcolor(BLACK);
textbackground(WHITE);
gotoxy(15,row);
cputs(opt[i]);
normvideo();
ch=getch();
switch(ch)
{
case 72: //UPARROW KEY (ASCII CODE) IS 72
row--;
row=row<11?15:row;
break;
case 80: //DOWN ARROW KEY
row++;
row=row>15?11:row;
break;
case 13: //ENTER KEY
flag=0;
}
i=row-10;
}
return(i);
}
int smenu()
{
int row,ch,i;
clrscr();
char sopt[4][20];
strcpy(sopt[1],"INDIVIDUAL");
strcpy(sopt[2],"LIST");

84
Compiled By Getinet
2010

strcpy(sopt[3],"RETURN TO MAIN");
row=11;
i=1;
int flag=1;
while(flag)
{
clrscr();
box(9,45,15,70);
gotoxy(50,11);
printf("%s",sopt[1]);
gotoxy(50,12);
printf("%s",sopt[2]);
gotoxy(50,13);
printf("%s",sopt[3]);
textcolor(BLACK);
textbackground(WHITE);
gotoxy(50,row);
cputs(sopt[i]);
normvideo();
ch=getch();
switch(ch)
{
case 72: //UPARROW KEY (ASCII CODE) IS 72
row--;
row=row<11?13:row;
break;
case 80: //DOWN ARROW KEY
row++;
row=row>13?11:row;
break;
case 13: //ENTER KEY
flag=0;
}
i=row-10;
}
return(i);
}
class bank
{
int acno,cbal;
char acname[10];
public:
void input()
{
clrscr();
box(8,10,16,70);

85
Compiled By Getinet
2010

gotoxy(15,10);
cout<<"ACCOUNT HOLDER NUMBER ";
cin>>acno;
gotoxy(15,12);
cout<<"ACCOUNT HOLDER NAME ";
cin>>acname;
gotoxy(15,14);
cout<<"ENTER CURRENT BALANCE ";
cin>>cbal;
}
void display()
{
box(5,10,13,50);
gotoxy(15,7);
cout<<"ACCOUNT HOLDER NUMBER "<<acno<<endl;
gotoxy(15,9);
cout<<"ACCOUNT HOLDER NAME "<<acname<<endl;
gotoxy(15,11);
cout<<"CURRENT BALANCE "<<cbal<<endl;
}
void show()
{
gotoxy(5,7);
cout<<acno<<"\t\t"<<acname<<"\t\t"<<cbal;
}
void putbal(int x)
{
cbal=x;
}
int getbal(void)
{
return cbal;
}
int getacno()
{
return acno;
}
int putacno(int y)
{
acno=y;
}
};

Popup Menu Program For Processing Bank.Dat File.

# include "my.h"

86
Compiled By Getinet
2010

void main()
{
int op=1,tacno;
bank b;
fstream fp,fp1;
while(op<5)
{
op=menu();
switch(op)
{
case 1:
clrscr();
fp.open("bank.dat",ios::in);
if(fp.good())
{
fp.read((char *)&b,sizeof(b));
while(!fp.eof())
{
tacno=b.getacno();
fp.read((char *)&b,sizeof(b));
}
tacno++;
}
else
tacno=100;
b.putacno(tacno);
b.input();
fp.close();
fp.open("bank.dat",ios::app);
fp.write((char *)&b,sizeof(b));
fp.close();
break;
case 2:
clrscr();
box(5,10,9,70);
gotoxy(15,7);
cout<<"ENTER ACCOUNT HOLDER NUMBER ";
cin>>tacno;
char tt;
int tamt,bal;
fp.open("bank.dat",ios::in | ios::out);
fp.read((char *)&b,sizeof(b));
int i=0;
while(tacno!=b.getacno() && !fp.eof())
{
i++;

87
Compiled By Getinet
2010

fp.read((char *)&b,sizeof(b));
}
if(!fp.eof())
{
clrscr();
b.display();
box(18,10,23,70);
gotoxy(15,19);
cout<<"ENTER TRANSACTION TYPE D/W ";
cin>>tt;
gotoxy(15,21);
cout<<"ENTER TRANSACTION AMOUNT ";
cin>>tamt;
if(tt=='d' || tt=='D')
bal=b.getbal()+tamt;
else
bal=b.getbal()-tamt;
if(bal>500)
{
b.putbal(bal);
fp.seekp((i*sizeof(b)),ios::beg);
fp.write((char *)&b,sizeof(b));
b.display();
}
else
{
box(20,5,23,70);
gotoxy(10,21);
cout<<"INSUFFICIENT FUNDS "<<tacno;
}
}
else
{
box(20,5,22,70);
gotoxy(10,21);
cout<<"ACCOUNT HOLDER NO NOT FOUND "<<tacno;
}
fp.close();
getch();
break;
case 3:
clrscr();
box(10,10,14,60);
gotoxy(15,12);
cout<<"ENTER HOLDER NO TO CANCEL ";
cin>>tacno;

88
Compiled By Getinet
2010

fp.open("bank.dat",ios::in);
fp1.open("tbank.dat",ios::out);
fp.read((char *)&b,sizeof(b));
int s=0;
while(!fp.eof())
{
if(tacno!=b.getacno())
fp1.write((char *)&b,sizeof(b));
else
s++;
fp.read((char *)&b,sizeof(b));
}
fp.close();
fp1.close();
remove("bank.dat");
rename("tbank.dat","bank.dat");
clrscr();
box(20,10,22,70);
if(s>0)
{
gotoxy(15,21);
cout<<"ACCOUNT CANCELLED SUCCESSFULLY "<<tacno<<endl;
}
else
{
gotoxy(15,21);
cout<<"ACCOUNT NO NOT FOUND "<<tacno<<endl;
}
getch();
break;
case 4:
int ch=0;
while(ch<3)
{
ch=smenu();
switch(ch)
{
case 1:
clrscr();
fp.open("bank.dat",ios::in);
box(10,10,14,60);
gotoxy(20,10);
cout<<"ENTER ACCOUNT HOLDER NUMBER ";
cin>>tacno;
clrscr();
fp.read((char *)&b,sizeof(b));

89
Compiled By Getinet
2010

while(tacno!=b.getacno() && !fp.eof())


fp.read((char *)&b,sizeof(b));
if(!fp.eof())
b.display();
else
{
box(20,10,22,60);
gotoxy(15,21);
cout<<"ACCOUNT HOLDER NUMBER NOT FOUND
"<<tacno<<endl;
}
getch();
fp.close();
break;
case 2:
clrscr();
box(1,3,4,75);
r=6;
gotoxy(32,2);
cout<<"ACCOUNT HOLDER LIST ";
gotoxy(5,3);
cout<<"ACNO"<<"\t\t"<<"AC
NAME"<<"\t\t"<<"BALANCE"<<endl;
fp.open("bank.dat",ios::in);
fp.read((char *)&b,sizeof(b));
int k=5;
while(!fp.eof())
{
b.show(k);
r++;
k++;
fp.read((char *)&b,sizeof(b));
}
r+=4;
box(4,3,r,75);
fp.close();
getch();
break;
} //switch end (sub menu)
} //while end (sub menu)
} //switch end (main menu)
} //while end (main menu)
} //main end

Sandeep Jewellers, Giddalur Maintains Different Files For This Sales And Stock
Information. They Are

90
Compiled By Getinet
2010

Ornament.Dat Cost.Dat
Ornament-Code Char[10] Type-Of-Ornament Char[2]
Ornament-Name Char[10] Current-Market-Rate Int
Weight Int
Type-Of-Ornament Char[10]

Customer.Dat
Customer-Number Int
Customer-Name Char[20]
Ornament-Code Char[10]
Number-Of-Items Int
Prepare A Bill For The Customer Using The Above Three Files And Print The Bill In
The Following Format

SANDEEP JEWELERIES AND PEARLS


GIDDALUR
CUSTOMER NUMBER:
CUSTOMER NAME:

ORNAMENT CODE:
ORNAMENT NAME:

WEIGHT:
CURRENT MARKET RATE: (per gram)
NUMBER OF ITEMS:

BILLED AMOUNT:

THANK YOU VISIT AGAIN

Two Types Of Ornaments Are Available Gold And Silver. The Corresponding Codes
Being G & S. The Current Market Rates Per Gram Is Available In The File Called
Cost.Dat Using Which The Bill To Be Prepared. (Assume That The Above Three Files
Are Already Contains Data In it).

//DATA STORING FOR ORNAMENT.DAT, COST.DAT, AND CUSTOMER.DAT


FILES
# include <iostream.h>
# include <conio.h>
# include <fstream.h>
class ornament
{

91
Compiled By Getinet
2010

char orcode[10],orname[10],ortype;
int wt;
public:
void input()
{
cout<<"ENTER ORNAMENT CODE ";
cin>>orcode;
cout<<"ENTER ORNAMENT NAME ";
cin>>orname;
cout<<"ENTER ORNAMENT TYPE S/G ";
cin>>ortype;
cout<<"ENTER ORNAMENT WEIGHT ";
cin>>wt;
}
};
class cost
{
char ortype;
int cmr;
public:
void accept()
{
cout<<"ENTER ORNAMENT TYPE S/G ";
cin>>ortype;
cout<<"ENTER CURRENT MARKET RATE ";
cin>>cmr;
}
};
class customer
{
int cno,noi;
char cna[10],orcode[10];
public:
void custin()
{
cout<<"ENTER CUSTOMER NUMBER ";
cin>>cno;
cout<<"ENTER CUSTOMER NAME ";
cin>>cna;
cout<<"ENTER ORNAMENT CODE G/S ";
cin>>orcode;
cout<<"ENTER NO. OF ITEMS ";
cin>>noi;
}
};
void main()

92
Compiled By Getinet
2010

{
ornament o;
cost c;
customer cust;
fstream fp;
fp.open("ornament.dat",ios::out);
clrscr();
char ch='y';
while(ch=='y' || ch=='Y')
{
o.input();
fp.write((char *)&o,sizeof(o));
cout<<"DO YOU WANT TO ADD ONE MORE RECORD Y/N ";
cin>>ch;
}
fp.close();
fp.open("cost.dat",ios::out);
clrscr();
ch='y';
while(ch=='y' || ch=='Y')
{
c.accept();
fp.write((char *)&c,sizeof(c));
cout<<"DO YOU WANT TO ADD ONE MORE RECORD Y/N ";
cin>>ch;
}
fp.close();
fp.open("customer.dat",ios::out);
ch='y';
while(ch=='y' || ch=='Y')
{
cust.custin();
fp.write((char *)&cust,sizeof(cust));
cout<<"DO YOU WANT TO ADD ONE MORE RECORD Y/N ";
cin>>ch;
}
fp.close();
}

Data Processing Program For Ornament.Dat, Cost.Dat And Customer.Dat Of The


Sandeep Jewelers.

//DATA PROCESSING FOR ORNAMENT.DAT, COST.DAT AND CUSTOMER.DAT


# include <iostream.h>
# include <conio.h>
# include <fstream.h>

93
Compiled By Getinet
2010

# include <string.h>
void pline()
{
for(int i=1;i<=80;i++)
cout<<"-";
}
class customer;
class cost;
class ornament
{
char orcode[10],orname[10],ortype;
int wt;
public:
void display()
{
gotoxy(1,10);
pline();
gotoxy(15,11);
cout<<"ORNAMENT CODE: "<<orcode;
gotoxy(15,12);
cout<<"ORNAMENT NAME: "<<orname;
gotoxy(1,13);
pline();
gotoxy(30,14);
cout<<"WEIGHT: "<<wt;
}
friend int calcamt(ornament o,customer c,cost s);
friend int chkcode(ornament o,customer c);
friend int chktype(ornament o,cost s);
};
class cost
{
char ortype;
int cmr;
public:
void out()
{
gotoxy(20,15);
cout<<"CURRENT MARKET RATE (1 gram): "<<cmr;
}
friend int chktype(ornament o,cost s);
friend int calcamt(ornament o,customer c,cost s);
};
class customer
{
int cno,noi;

94
Compiled By Getinet
2010

char cna[10],orcode[10];
public:
void output()
{
gotoxy(1,8);
pline();
gotoxy(5,9);
cout<<"CUSTOMER NUMBER: "<<cno;
gotoxy(40,9);
cout<<"CUSTOMER NAME: "<<cna;
gotoxy(20,16);
cout<<"NUMBER OF ITEMS: "<<noi;
gotoxy(1,17);
pline();
}
friend int calcamt(ornament o,customer c,cost s);
friend int chkcode(ornament o,customer c);
};
int calcamt(ornament o,customer c,cost s)
{
int b;
b=(o.wt*s.cmr*c.noi);
return(b);
}
int chkcode(ornament o,customer c)
{
if(stricmp(o.orcode,c.orcode)==0)
return 1;
else
return 0;
}
int chktype(ornament o,cost s)
{
if(o.ortype==s.ortype)
return 1;
else
return 0;
}
void main()
{
ornament o;
cost c;
customer cust;
int bamt;
fstream fp,fp1,fp2;
fp.open("customer.dat",ios::in);

95
Compiled By Getinet
2010

fp.read((char *)&cust,sizeof(cust));
while(!fp.eof())
{
fp1.open("ornament.dat",ios::in);
fp2.open("cost.dat",ios::in);
fp1.read((char *)&o,sizeof(o));
while(chkcode(o,cust)==0 && !fp1.eof())
fp1.read((char *)&o,sizeof(o));
if(fp1.eof())
cout<<"ORNAMENT CODE NOT FOUND ";
else
{
fp2.read((char *)&c,sizeof(c));
while(chktype(o,c)==0 && !fp2.eof())
fp2.read((char *)&c,sizeof(c));
if(fp2.eof())
cout<<"ORNAMENT TYPE NOT FOUND "<<endl;
else
{
clrscr();
bamt=calcamt(o,cust,c);
gotoxy(1,4);
pline();
gotoxy(30,5);
cout<<"LOKKU-IZA JEWELLERS";
gotoxy(35,6);
cout<<"MAIN BAZAR";
gotoxy(37,7);
cout<<"GIDDALUR";
cust.output();
o.display();
c.out();
gotoxy(20,18);
cout<<"BILL AMOUNT: "<<bamt;
gotoxy(1,19);
pline();
}
}
fp1.close();
fp2.close();
getch();
fp.read((char *)&cust,sizeof(cust));
}
fp.close();
}

96
Compiled By Getinet
2010

TEXT PROCESSING

C++ provides some functions to process the text files instead of data files. Text files
can open in the same way as you open the data files. C++ file stream classes provides some
functions to write or read text from files. You can process the text files by using the
following functions.

get() function: This function gets a string from a file stream.


Syntax: streamobject.get();

get() reads character from stream and returns a single character.


e.g.: fp.get();
put() function: Outputs a character on to a stream.
Syntax: streamobject.put(char ch);

Put() copies a single character ch to the given output stream.


E.g.: fp.put(ch);

Read A File Name And Print Its Contents In Upper Case.

# include <stdlib.h>
# include <ctype.h>
# include <iostream.h>
# include <fstream.h>
# include <conio.h>
# include <dos.h>
void main()
{
char fn[40],ch;
fstream fp;
clrscr();
cout<<"ENTER A FILE NAME WITH EXTENSION :";
cin>>fn;
fp.open(fn,ios::in);
if(!fp.good())
{
cout<<"FILE NOT FOUND "<<endl;
getch();
exit(0);
}
clrscr();
fp.get(ch);
while(!fp.eof())
{
cout<<(char)toupper(ch);
fp.get(ch);

97
Compiled By Getinet
2010

delay(200);
}
fp.close();
getch();
}

Read A File Name And Create A Text File With The Specified Name.

# include <stdlib.h>
# include <iostream.h>
# include <fstream.h>
# include <io.h>
# include <conio.h>
void main()
{
char fn[20],ch;
fstream fp;
clrscr();
cout<<"ENTER FILE NAME YOU WANT TO CREATE :";
cin>>fn;
if(access(fn,0) == 0)
{
cout<<"FILE IS ALREADY EXISTS"<<fn<<endl;
getch();
exit(0);
}
fp.open(fn,ios::out);
clrscr();
cout<<"ENTER THE CONTENTS '/' TO SHOP :"<<endl;
ch=getche();
while(ch!='/')
{
fp.put(ch);
ch=getche();
if(ch == 13)
{
fp.put('\n');
cout<<endl;
}
}
fp.close();
}

98
Compiled By Getinet
2010

Write A Program To Read Source File Name And Target File Name And Copy The
Contents Of Source File To Target File.

# include <conio.h>
# include <stdlib.h>
# include <iostream.h>
# include <fstream.h>
# include <io.h>
void main()
{
char sfn[20],tfn[20],ch;
fstream fp,fp1;
clrscr();
cout<<"ENTER SOURCE FILE NAME YOU WANT TO COPY :";
cin>>sfn;
if(access(sfn,0) == 0)
{
cout<<"ENTER TARGET FILE NAME TO COPY :";
cin>>tfn;
if(access(tfn,0) != 0)
{
fp.open(sfn,ios::in);
fp1.open(tfn,ios::out);
clrscr();
fp.get(ch);
while(!fp.eof())
{
cout<<ch;
fp1.put(ch);
fp.get(ch);
}
fp.close();
fp1.close();
cout<<sfn<<"CPOIED IN TO :"<<tfn<<"SUCCESSFULLY"<<endl;
}
else
cout<<"TARGET FILE ALREADY EXISTS:"<<tfn<<endl;
}
else
cout<<"SOURCE FILE DOES NOT EXISTS :"<<sfn<<endl;
getch();
}
COMMAND LINE ARGUMENTS.

99
Compiled By Getinet
2010

C supports a feature that facilities the supply of arguments to the main() function.
These arguments are supplied at the time of invoking the program. They are typically used
to pass the names of data files. For example

C:\>EXAM DATA RESULTS

Here exam is the name of the file contains the program to be executed and data and
results are the file names passed to the program as command line arguments.

The command line arguments are typed by the user and are delimited by a space.
The first argument is always the file name and contains the program to be executed. The
main() function which we have been using up to now without any arguments can take two
arguments as shown below.

void main(int argc, char *argv[ ])

The first argument argc is known as argument counter represents the number of
arguments in the command line. The second argument argv is known as argument vector is
an array of char type pointer that point to the command line arguments. The size of this
array will be equal to the value of argc. For example
C:\>EXAM DATA RESULTS

The value of argc would be 3 and argv would be an array of 3 pointers to strings as
shown below
argv[0]--------- exam
argv[1]--------- data
argv[2]--------- results

Note that argv[0] always represents the command name that invokes the program.

Example Program For Command Line Arguments.

# include <stdio.h>
# include <conio.h>
# include <process.h>
# include <iostream.h>
void main(int argc,char *argv[])
{
if(argc == 1)
{
cout<<"REMIND ARGUMENT IS MISSING:";
getch();
exit(0);
}
else

100
Compiled By Getinet
2010

{
clrscr();
cout<<"TOTAL ARGUMENTS :"<<argc<<endl;
for(int i=0;i<argc;i++)
cout<<"THE ARGUMENT "<<"IS"<<argv[i]<<endl;
}
getch();
}

Read A File Name Through Command Line Arguments And Write A Program To Find
Out Where The File Is Existed In The Current Directory Or No.

# include <iostream.h>
# include <conio.h>
# include <process.h>
# include <io.h>
void main(int argc,char *argv[])
{
if(argc == 1)
{
cout<<"REQUIRED ARGUMENT IS MISTIFY :";
exit(0);
}
else if(argc > 2)
{
cout<<"TOO MANY ARGUMENTS :"<<endl;
exit(0);
}
else if(access(argv[1],0) == 0)
cout<<"FILE EXISTS IN THE CURRENT DIRECTORY
"<<argv[1]<<endl;
else
cout<<"FILE NOT FOUND "<<argv[1]<<endl;
}

Read A File Name Through Command Line Arguments And Delete That File.

STRUCT FTBLK <DIR.H>

101
Compiled By Getinet
2010

DOS file control block structure.

struct ftblk
{
char ft_reserved[21]; //reserved by dos
char ft_altlib; //altlib found
int ft_ftime; //file time
int ft_fdate; //file date
int ft_size; //file size
int ft_name[13]; //found file name
};
find first() //<dir.h>

find first search a disk directory for files.

Syntax: int findfirst(const char *pathname, struct ftblk *ftblk, int altlib);

Find first begins a search of a disk directory path name string with an optional drive
specifies path and file name of the file to be found. The file name portion can contain wild
card match characters ( ?, *).

Ftblk: points to ftblk structure that is filled with the file_directory information it findfirst
and find next finds a file that matches path name.

Altlib: dos file_alttribute byte(define in dos.h) used to eligible files for the search. Dos file
attributes are

CONSTANT DESCRIPTION

FA_RDONLY Read only attribute

FA_HIDDEN Hidden file

FA_SYSTEM System file

FA_LABEL Volume label

FA_DIREC Directory

FA_ARCH Archive

On success ( a match was found) this function return 0, on error( no more files can
be found there is some error in the file name) return -1.

102
Compiled By Getinet
2010

FINDNEXT(): <DIR.H>
Findnext() continue the search for files.

Syntax: int findnext(struct ftblk *ftblk);


Findnext() find subsequent files that match the path name argument of find first()
Ftblk(): points to ftblk structure that is filled with file directory information
findnext() finds a file that matches path name.

For each call to findnext() one file name will be returned until no more files are
found in the directory specified in path name.

Write A Program To Display The Files List From The Current Directory. Using
Command Line Arguments.

Dflcurdi.cpp

City Library Has Computerized Its Work. They Have Maintaining 3 Files For Books,
Members And Transactions. They Are

Books Members Transactions


Bcode Number 4 Mno Number10 Mno Number10
Bname String 30 M-Name String 20 Bcode Number 4
Aname String 30 M-Add String 20 Bname String 30
Status String 1 Book-Taken Number 3 Tdate Date
Rdate Date
Nod Number 2
Change Number 6,2

Write A Program To Satisfy The Following Menu Options.

LIBRARY MENU

1. ADD NEW BOOK.


2. ADD NEW MEMBER.
3. BOOK ISSUED.
4. BOOK RETURN.
5. BOOK STATUS.
6. EXIT.

1. If you choose first option new book will be added to the book table. Book code will be
automatically generated.
2. If you choose second option member information will be added to member table. The
will be 0.

103
Compiled By Getinet
2010

3. If you choose third option a member can issue a book. Maximum number of books
issued=3. At the time of issuing we have to enter book name. If the status is 'y' then
he can take the book name.
4. If you choose fourth option the return date will be system date and the change will be
3 rupees daily.
5. If you choose fifth option accept the book name and display the status from the data
file in your own format.
6. If you choose sixth option exits from the main menu.
Library program.

LINKED LIST.

A list refers to a set of items organized sequentially. An array is an example of list.


In an array, the sequential organization is provided implicitly by its index. We use the
index for accessing and manipulation of array elements. One major problem with the array
is that the size of an array must be specified at the beginning. This may be a difficult task in
many practical applications.

A completely different way to represent a list is that make each item in the list part
of a structure. That also contains a link to the structure contains the next item as shown in
the following manner.

NEXT NEXT NEXT

X Y

RNO XXX RNO XXX


NEXT NEXT

This type of list is called "linked list" because it is a list whose order is given by
from one item to the next. Each structure of the list is called a node and consists of two
fields one containing data and the other containing the address of the next item ( a pointer
to the next item) in the list. A linked list is therefore a collection of structure ordered not by
their physical placements members but by logical links that are stored as part of the data in
the structure itself. A link is in structure is represented as follows.

struct test
{
int a;
struct test *p;
};

104
Compiled By Getinet
2010

The first member is integer a and the second a pointer to the next address in the list
as shown below.
Test

A P

Syntax: struct tagname


{
type member1;
type member2;
- -------- -
- - - - - - - -- -
struct tagname *next;
};

Structures which contain a member field that points to the same structure type is
called "self referential structures". The structure may contain more than one item
different data types. How ever one of the items must be the pointer of the type tagname.
E.g.: struct link
{
int sno;
struct link *next;
};
struct link x,y;
xnext=&y;
xnext=sno;
x=xnext;
xsno;

SNO NEXT SNO NEXT

The above statement stores the address of 'y' in to the field x.next and this
establishes a link between x and y. x.next contains the address of y where the value of the
variable y.sno will be stored. We may continue this process to create a linked list of any
number of values.

Every list must have an end, we must there fore indicate the end of a linked list.
This is necessary for processing the list. C has a special pointer value as "NULL" that can
be stored in the next field other last structure in our structured list. The end of the list is
marked as follows
y.next=NULL;
The value of the sno of y can be accessed using the next member of x as follows

105
Compiled By Getinet
2010

Printf("%d",x.nextsno);

ADVANTAGES OF LINKED LIST.

A linked list is a dynamic data structure there fore the primary advantages of linked
list over arrays is that linked list can glow or shrink in size during the execution of a
program.

Another advantage is linked list does not waste memory space. It uses the memory
that is just needed at any point of time. That is because, it is not necessary to specify the
number of nodes to be used for the list.

The third and more important advantage is that the linked list is provided flexibility
in allowing the items to be reading efficiently. It is easy to insert or delete items by
rearranging the lists.

TYPES OF LINKED LIST.

1. Linear linked list or single linked list.


2. Two-way linked list or double linked list.
3. Circular single linked list.
4. Circular double linked list.

Example Program For SINGLE LINKED LIST.

# include <malloc.h>
# include <stdio.h>
# include <conio.h>
struct node
{
int info;
struct node *next;
};
struct node *create()
{
struct node *root,*prev,*new1;
int temp,size;
size=sizeof(struct node);
printf("\n Enter the integers or -999 to stop ");
scanf("%d",&temp);
printf("%d\n",temp);
prev=root=NULL;
while(temp!=-999)
{
new1=(struct node *)malloc(size);
new1->info=temp;

106
Compiled By Getinet
2010

new1->next=NULL;
if(root==NULL)
root=new1;
else
prev->next=new1;
prev=new1;
scanf("%d",&temp);
printf("%d\n",temp);
}
return root;
}
void display(start)
struct node *start;
{
printf("\nROOT->");
while(start!=NULL)
{
printf("%d->",start->info);
start=start->next;
}
printf("NULL\n\n");
}
void insert(start,new_info,posn)
struct node **start;
int new_info,posn;
{
struct node *new_node,*temp;
int i;
new_node=(struct node *)malloc(sizeof(struct node));
new_node->info=new_info;
if((posn==1) || ((*start)==NULL))
{
new_node->next=*start;
*start=new_node;
}
else
{
temp=*start;
i=2;
while((i<posn) && (temp->next!=NULL))
{
temp=temp->next;
++i;
}
new_node->next=temp->next;
temp->next=new_node;

107
Compiled By Getinet
2010

}
}
int delete1(start,posn)
struct node **start;
int posn;
{
struct node *temp;
int i,return_value=1;
if(*start!=NULL)
if(posn==1)
*start=(*start)->next;
else
{
temp=*start;
i=2;
while((temp->next!=NULL) && (i<posn))
{
temp=temp->next;
++i;
}
if(temp->next!=NULL)
temp->next=temp->next->next;
else
return_value=0;
}
else
return_value=0;
return return_value;
}
void main()
{
struct node *root;
int new_info,posn,quit;
char c;
root=NULL;
quit=0;
do
{
printf("Create/Insert/Delete/Quit(C/I/D/Q)");
printf("\nEnter your choice ");
do
c=getchar();
while(strchr("cCiIdDqQ",c)==NULL);
printf("%c\n",c);
switch(c)
{

108
Compiled By Getinet
2010

case 'c':
case 'C':
root=create();
printf("\n The Created linked list is ");
display(root);
break;
case 'i':
case 'I':
printf("\n Enter element to be inserted ");
scanf("%d",&new_info);
printf("%d\n",new_info);
do
{
printf("Enter the position of insertion ");
scanf("%d",&posn);
printf("%d\n",posn);
}while(posn<1);
insert(&root,new_info,posn);
printf("\nThe linked list after creation is\n");
display(root);
break;
case 'd':
case 'D':
do
{
printf("Enter the position of deletion ");
scanf("%d",&posn);
printf("%d\n",posn);
}while(posn<1);
if(!delete1(&root,posn))
printf("\n Cannot delete element at position
%d.\n\n",posn);
else
{
printf("The linked list after deletion is \n");
display(root);
}
break;
case 'q':
case 'Q':
quit=1;
}
}while(!quit);
printf("\n");
}

109
Compiled By Getinet
2010

DOUBLE WAY LINKED LIST.

The double way linked list uses double set of pointers one pointing to the next item
and other pointing to the preceding item. This allows us to travels the list in either
direction.

In single linked list, the travelling of nodes is available in only one direction. That is
from one end to another end we can move from a current node to next node but not to the
previous node. So when you want to refer the node that just crossed is not possible in single
linked list to refer. For that we have to start from the first node to refer that particular node.
To avoid this problem, the double linked lists were introduced. In general format of the
node in double way linked list is as follow

PREVIOUS N NEXT

The previous pointer points to the previous node and the next pointer points to the
next node. Information is the actual data available in that node.

Exaple Program For DOUBLE WAY LINKED LIST.

# include <malloc.h>
# include <stdio.h>
# include <conio.h>
struct node
{
int info;
struct node *back,*next;
};
struct node *create(last)
struct node **last;
{
struct node *root,*prev,*new1;
int new_info,size;
size=sizeof(struct node);
printf("\n Enter the integers or -999 to stop:");
scanf("%d",&new_info);
printf("%d\n",new_info);
prev=root=*last=NULL;
while(new_info!=-999)
{
new1=(struct node *)malloc(size);
new1->info=new_info;

110
Compiled By Getinet
2010

new1->next=NULL;
if(root==NULL)
{
root=new1;
new1->back=NULL;
}
else
{
prev->next=new1;
new1->back=prev;
}
prev=new1;
scanf("%d",&new_info);
printf("%d\n",new_info);
}
if(root!=NULL)
*last=new1;
return root;
}
void display(start,end)
struct node *start,*end;
{
printf("\nForward Direction.\nROOT<=>");
while(start!=NULL)
{
printf("%d<=>",start->info);
start=start->next;
}
printf("END\n\n");
printf("\nReverse Direction.\nEnd<=>");
while(end!=NULL)
{
printf("%d<=>",end->info);
end=end->back;
}
printf("Root\n\n");
}
void insert(start,last,new_info,posn)
struct node **start,**last;
int new_info,posn;
{
struct node *new_node,*temp;
int i;
new_node=(struct node *)malloc(sizeof(struct node));
new_node->info=new_info;
if((posn==1) || ((*start)==NULL))

111
Compiled By Getinet
2010

{
new_node->next=*start;
if(*start!=NULL)
(*start)->back=new_node;
*start=new_node;
new_node->back=NULL;
}
else
{
temp=*start;
i=2;
while((i<posn) && (temp->next!=NULL))
{
temp=temp->next;
++i;
}
new_node->next=temp->next;
if(temp->next!=NULL)
temp->next->back=new_node;
new_node->back=temp;
temp->next=new_node;
}
if(new_node->next==NULL)
*last=new_node;
}
int delete1(start,last,posn)
struct node **start,**last;
int posn;
{
struct node *temp;
int i,return_value=1;
if(*start!=NULL)
if(posn==1)
{
*start=(*start)->next;
if(*start!=NULL)
(*start)->back=NULL;
else
*last=NULL;
}
else
{
temp=*start;
i=2;
while((temp->next!=NULL) && (i<posn))
{

112
Compiled By Getinet
2010

temp=temp->next;
++i;
}
if(temp->next!=NULL)
{
temp->next=temp->next->next;
if(temp->next==NULL)
*last=temp;
else
temp->next->back=temp;
}
else
return_value=0;
}
else
return_value=0;
return return_value;
}
void main()
{
struct node *root,*last;
int new_info,posn,quit;
char c;
root=NULL;
quit=0;
do
{
printf("Create/Insert/Delete/Quit(C/I/D/Q)");
printf("\nEnter your choice ");
do
c=getchar();
while(strchr("cCiIdDqQ",c)==NULL);
printf("%c\n",c);
switch(c)
{
case 'c':
case 'C':
root=create(&last);
printf("\n The Created linked list is ");
display(root,last);
break;
case 'i':
case 'I':
printf("\n Enter element to be inserted ");
scanf("%d",&new_info);
printf("%d\n",new_info);

113
Compiled By Getinet
2010

do
{
printf("Enter the position of insertion ");
scanf("%d",&posn);
printf("%d\n",posn);
}while(posn<1);
insert(&root,&last,new_info,posn);
printf("\nThe linked list after creation is\n");
display(root,last);
break;
case 'd':
case 'D':
do
{
printf("Enter the position of deletion ");
scanf("%d",&posn);
printf("%d\n",posn);
}while(posn<1);
if(!delete1(&root,&last,posn))
printf("\n Cannot delete element at position
%d.\n\n",posn);
else
{
printf("The linked list after deletion is \n");
display(root,last);
}
break;
case 'q':
case 'Q':
quit=1;
}
}while(!quit);
printf("\n");
}

CIRCULAR LINKED LIST.

In an ordinary linked lists we can not travels all the elements when we start from
the middle node of the list. To avoid this problem the circular lists were introduced. In
circular lists we can travel all the elements from when you start from any node in the list.
To prepare circular list maintains the address of the first node in the last node of the list.

Example Program For CIRCULAR LNKED LIST.

# include <malloc.h>
# include <stdio.h>

114
Compiled By Getinet
2010

# include <conio.h>
struct node
{
int info;
struct node *next;
};
struct node *create(last)
struct node **last;
{
struct node *root,*new1;
int temp,size;
size=sizeof(struct node);
printf("\n Enter the integers or -999 to stop ");
scanf("%d",&temp);
printf("%d\n",temp);
*last=root=NULL;
while(temp!=-999)
{
new1=(struct node *)malloc(size);
new1->info=temp;
if(root==NULL)
root=new1;
else
(*last)->next=new1;
(*last)=new1;
scanf("%d",&temp);
printf("%d\n",temp);
}
if(root!=NULL)
new1->next=root;
return root;
}
void display(start,last)
struct node *start,*last;
{
printf("\nROOT->");
if(start!=NULL)
{
do
{
printf("%d->",start->info);
start=start->next;
}while(last->next!=start);
printf("Root\n\n");
}
else

115
Compiled By Getinet
2010

printf("NULL\n\n");
}
void insert(start,last,new_info,posn)
struct node **start,**last;
int new_info,posn;
{
struct node *new_node,*temp;
int i;
new_node=(struct node *)malloc(sizeof(struct node));
new_node->info=new_info;
if((posn==1) || ((*start)==NULL))
{
new_node->next=*start;
*start=new_node;
if((*last)!=NULL)
(*last)->next=*start;
else
*last=*start;
}
else
{
temp=*start;
i=2;
while((i<posn) && (temp->next!=NULL))
{
temp=temp->next;
++i;
}
if(temp->next==(*start))
*last=new_node;
new_node->next=temp->next;
temp->next=new_node;
}
}
int delete1(start,last,posn)
struct node **start,**last;
int posn;
{
struct node *temp;
int i,return_value=1;
if(*start!=NULL)
if(posn==1)
{
if((*start)->next!=*start)
{
*start=(*start)->next;

116
Compiled By Getinet
2010

(*last)->next=*start;
}
else
*start=*last=NULL;
}
else
{
temp=*start;
i=2;
while((temp->next!=NULL) && (i<posn))
{
temp=temp->next;
++i;
}
if(temp->next!=NULL)
{
if(temp->next==*last)
*last=temp;
temp->next=temp->next->next;
}
else
return_value=0;
}
else
return_value=0;
return return_value;
}
void main()
{
struct node *root,*last;
int new_info,posn,quit;
char c;
clrscr();
root=NULL;
quit=0;
do
{
printf("Create/Insert/Delete/Quit(C/I/D/Q)");
printf("\nEnter your choice ");
do
c=getchar();
while(strchr("cCiIdDqQ",c)==NULL);
printf("%c\n",c);
switch(c)
{
case 'c':

117
Compiled By Getinet
2010

case 'C':
root=create(&last);
printf("\n The Created linked list is ");
display(root,last);
break;
case 'i':
case 'I':
printf("\n Enter element to be inserted ");
scanf("%d",&new_info);
printf("%d\n",new_info);
do
{
printf("Enter the position of insertion ");
scanf("%d",&posn);
printf("%d\n",posn);
}while(posn<1);
insert(&root,&last,new_info,posn);
printf("\nThe linked list after creation is\n");
display(root,last);
break;
case 'd':
case 'D':
do
{
printf("Enter the position of deletion ");
scanf("%d",&posn);
printf("%d\n",posn);
}while(posn<1);
if(!delete1(&root,&last,posn))
printf("\n Cannot delete element at position
%d.\n\n",posn);
else
{
printf("The linked list after deletion is \n");
display(root,last);
}
break;
case 'q':
case 'Q':
quit=1;
}
}while(!quit);
printf("\n");
}
QUEUES AND STACKS.

118
Compiled By Getinet
2010

These are the programs consist of algorithm and data structures. The good program
is a blend of both choosing and implementing a data structure are as important as the
routines that manipulate the data. How information is organized and accessed is usually
determined by the nature of the programming problem. There fore as a programmer you
must have in your bag of tricks. The right storage and retrieval methods for any situation.

The actual representing of data in the computer is built from the ground up starting
with the data types like char, int and float. At the next level are arrays, which are organized
collections of the data types. Next there are structures, which are different data types
accessed under one name. Transcending these physical aspects of data. The final level
concentrates on the sequence in which the data will be stored and retrieved. In essence the
physical data is linked to data machines, that controls the way your program accesses the
information. These 4 of these machines
1. A STACK.
2. A QUEUE.
3. A LINKED LIST.
4. A BINARY TREE.
Each method provides a solution to a class of problems, each is essentially a device
that performs a specific storage an retrieval operation o n the given information and
request. The methods share two operations store an item and retrieve an item in which the
item is one information unit.
STACKS.
A stack is the opposite of a queue, because it uses last in first out accessing (LIFO).
Imagine a stack of plates the bottom plate in the stack is the last to be used and the top plate
(the last plate on the stack) is the first to be used
QUEUES.
A queue is a linear list of information that is accessed in first in first out order
(FIFO). The first item placed on the queue is the first item retrieved, the second item placed
on the queue is the second item retrieved and so on.
Example Program For QUEUES.

# include <stdio.h>
# include <conio.h>
struct queue
{
int item[100];
int f,r;
}q;
void qinsert(void);
void qdelete(void);
void qdisplay(void);
void main()
{
int resp=0;
clrscr();
q.f=1;

119
Compiled By Getinet
2010

q.r=0;
while(resp<=3)
{
printf("\n\t QUEUE OPERATIONS ");
printf("\n1.Insert an element ");
printf("\n2.Delete an element ");
printf("\n3.Display queue ");

printf("\n4.Exit ");
printf("\n\nYour Choice ");
scanf("%d",&resp);
switch(resp)
{
case 1:
qinsert();
break;
case 2:
qdelete();
break;
case 3:
qdisplay();
break;
case 4:
break;
}
}
}
void qinsert()
{
int x;
printf("\nType the element ");
scanf("%d",&x);
q.r++;
q.item[q.r]=x;
}
void qdelete()
{
int x;
x=q.item[q.f];
++q.f;
printf("\nDeleted element %d ",x);
}
void qdisplay()
{
int i;
printf("\nThe Queue elements are \n");

120
Compiled By Getinet
2010

for(i=q.f;i<=q.r;i++)
printf("%d\t",q.item[i]);
}

Example Program For STACKS.

# include <stdio.h>
# include <conio.h>
struct element
{
int item[100];
int top;
};
struct element s;
void push(int x);
void pop();
void main()
{
int n,i,x;
s.top=0;
printf("\nEnter how many elements (Below 100) ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter an element ");
scanf("%d",&x);
push(x);
}
printf("\n The given elements are \n");
for(i=0;i<n;i++)
pop();
getch();
}
void push(int x)
{
s.top++;
s.item[s.top]=x;
}
void pop()
{
printf("%d ->",s.item[s.top]);
s.top--;
}

Example Program For Perform Operations On BINARY TREES On Integers.

121
Compiled By Getinet
2010

# include <stdio.h>
# include <malloc.h>
# include <conio.h>
struct node
{
int val;
struct node *lptr,*rptr;
};
struct node *str;
int ch,d,td;
void dep(str)
struct node *str;
{
if(str->lptr==NULL)
if(d<td)
d=td;
else;
else
{
td++;
dep(str->lptr);
}
if(str->rptr==NULL)
if(d<td)
d=td;
else;
else
{
td++;
dep(str->rptr);
}
td--;
}
void pred(str)
struct node *str;
{
if(str!=NULL)
{
printf("%i",str->val);
pred(str->lptr);
pred(str->rptr);
}
}
void ind(str)
struct node *str;
{

122
Compiled By Getinet
2010

if(str!=NULL)
{
ind(str->lptr);
printf("%i",str->val);
ind(str->rptr);
}
}
void postd(str)
struct node *str;
{
if(str!=NULL)
{
postd(str->lptr);
postd(str->rptr);
printf("%i",str->val);
}
}
void disp()
{
do
{
printf("1-Pre Order,2-In Order,3-Post Order.\n");
scanf("%i",&ch);
printf("%i\n",ch);
switch(ch)
{
case 1:
pred(str);
break;
case 2:
ind(str);
break;
case 3:
postd(str);
}
}while(ch<1 || ch>3);
printf("\n");
}
void ins()
{
struct node *temp,*prev;
int n,c,ef;
clrscr();
do
{
printf("How Many Elements :");

123
Compiled By Getinet
2010

scanf("%i",&n);
fflush(stdin);
printf("%i\n",n);
}while(n<1);
do
{
printf("Enter The Value For The Node :");
scanf("%i",&c);
fflush(stdin);
printf("%i\n",c);
temp=str;
ef=0;
if(temp==NULL)
{
str=(struct node*)malloc(sizeof(struct node));
temp=str;
}
else
{
while(temp!=NULL && !ef)
{
prev=temp;
if(c==temp->val)
{
printf("%i is Already Persent In The Tree!",c);
printf("\n");
ef=1;
}
else
if(c<temp->val)
temp=temp->lptr;
else
temp=temp->rptr;
}
if(!ef)
{
temp=(struct node*)malloc(sizeof(struct node));
if(c<prev->val)
prev->lptr=temp;
else
prev->rptr=temp;
}
}
if(!ef)
{
temp->val=c;

124
Compiled By Getinet
2010

temp->lptr=NULL;
temp->rptr=NULL;
n--;
}
}while(n>0);
}
void sear(c,par,loc)
int c;
struct node **par,**loc;
{
*par=NULL;
*loc=NULL;
while(*loc!=NULL && (*loc)->val!=c)
{
*par=*loc;
if(c<(*loc)->val)
(*loc)=(*loc)->lptr;
else
(*loc)=(*loc)->rptr;
}
}
void del1(loc, par)
struct node *loc,*par;
{
struct node *temp;
if(loc->lptr==NULL)
temp=loc->rptr;
else
temp=loc->rptr;
if(par!=NULL)
if(loc==par->lptr)
par->lptr=temp;
else
par->rptr=temp;
else
str=temp;
}
void del2(loc,par)
struct node *par,*loc;
{
struct node *suc,*parsuc;
suc=loc->rptr;
parsuc=loc;
while(suc->lptr!=NULL)
{
parsuc=suc;

125
Compiled By Getinet
2010

suc=suc->lptr;
}
del1(suc,parsuc);
if(par!=NULL)
if(loc==par->lptr)
par->lptr=suc;
else
par->rptr=suc;
else
str=suc;
suc->lptr=loc->lptr;
suc->rptr=loc->rptr;
}
void del()
{
struct node *loc,*par;
int n,c;
do
{
printf("How Many Elements :");
scanf("%i",&n);
fflush(stdin);
printf("%i\n",n);
}while(n<1);
do
{
printf("Enter The Element :");
scanf("%i",&c);
fflush(stdin);
printf("%i\n",c);
sear(c,&par,&loc);
if(loc==NULL)
printf("Element Not Found\n");
else
if(loc->lptr!=NULL && loc->rptr!=NULL)
del2(loc,par);
else
del1(loc,par);
n--;
}while(n>0);
}
void main()
{
str=NULL;
printf("Operations On Binary Tree.\n");
do

126
Compiled By Getinet
2010

{
printf("1-Insert,2-Delete,3-Display,4-Depth,");
printf("5-Quit.\n");
scanf("%i",&ch);
printf("%i\n",ch);
switch(ch)
{
case 1:
ins();
break;
case 2:
del();
break;
case 3:
disp();
break;
case 4:
if(str==NULL)
printf("Tree Empty !");
else
{
d=0;
td=0;
dep(str);
printf("Depth Of This Tree :%i\n",d);
}
break;
case 5:
printf("Good Bye !\n");
}
}while(ch!=5);
}

<GRAPHICS.H>

This header file contains all the functions related to graphics mode.

Initgraph(): Initializes the graphics system.


Syntax: initgraph(int *graphdriver, int *graphmode, char *pathtodriver)

To start the graphics system, you must first call initgraph(). Initgrapg() initializes
the graphics system by loading a graphics drive from disk then putting the system into
graphics mode.

*graphdriver(): Integer that specifies the graphics driver to be used. You can give graph
driver a value using a constant of the graphics-drivers enumeration type.

127
Compiled By Getinet
2010

*graphmode: Integer that specifies the initial graphics mode. If *graphdriver=DETECT


initgraph sets *graphmode to the highest resolution available for the detected driver.

*pathtodriver(): Specifies the directory path where initgraph looks for graphics drivers.
*graphmode and *graphdriver must set to valid graphics-drivers and graphics-mode values
or you will get unpredictable results. If you tell init graph to autodetect, it calls detect graph
to select a graphics driver and mode.
Graphresult(): Returns an error code for the last unsuccessful graphics operation.
Syntax: int graphresult();

Graphresult() returns the error code for the last graphics operation that reported an
error then resets the error level to grok. Returns the current graphics error number, (an
integer range -15 to 0).

Grapherrormsg(): Returns a pointer to an error message string.

Syntax: char * grapherrormsg(int error code)

Graph error message returns a pointer to the error message string associated with
error code, the value returned by graph result.

Outtext(): displays a string in a graphics mode. Using current justification settings,


font, direction and size.

Syntax: outtext(char textstring);

Outtextxy(): Displays a string at a specified location.

Syntax: outtextxy(int x,int y,char textstring);

Otutextxy() displays a text string at the given position x, y using current


justification settings current font directions and size.
e.g.: outtext("THOMAS SUGUNAKAR RAJA");
outtextxy(150,200,"SANDEEP KUMAR");

Settextstyle(): Sets the currrent text characteristics for graphics output.

Syntax: settextstyle(int font, int direction, int size);

Sets the text font, the direction in which the text is displayed and the size of the
characters. A call to settextstyle() effects all text output by outtext() and outtextxy().

Font: It allows the following fonts.

128
Compiled By Getinet
2010

NAME VALUE MEANING

DEFAULT_FONT 0 8X8 bit mapped font.


TRIPLEX_FONT 1 Stroked triplex font.
SMALL_FONT 2 Stroked small font.
SANS_SERIF_FONT 3 Stroked sans serif font.
GOTHIC_FONT 4 Stroked gothic font.
SCRIPT_FONT 5 Stroked script font.
SIMPLEX_FONT 6 Stroked simplex font.
TRIPLEX_SCR_FONT 7 Stroked triplex scr font.
COMPLEX_FONT 8 Stroked complex font.
EUROPEAN_FONT 9 Stroked European font.
BOLD_FONT 10 Stroked bold font.

HORIZ_DIR 0 Horizontal direction


VERT_DIR 1 Vertical direction.

Direction Specifies the direction of the text.


Size The size of the each character can be magnified using the size factor.

Setcolor(): Sets the current drawing color.


Syntax: setcolor(int color);

Setcolor() sets the current drawing color to color, which can range from 0 to
getmaxcolor. To select a drawing color with setcolor. You can pass either the color number
or the equaling color name. The drawing color is the value that pixels are set to when the
program draws lines etc. You can use the following colors.

COLOR VALUE

BLACK 0
BLUE 1
GREEN 2
CYAN 3
RED 4
MAGENTA 5
BROWN 6
LIGHT GRAY 7
DARK GRAY 8
LIGHT BLUE 9
LIGHT GREEN 10

129
Compiled By Getinet
2010

LITGHT CYAN 11
LIGHT RED 12
LIGHT MAGENTA 13
YELLOW 14
WHITE 15

Getcolor(): getcolor() returns the current drawing color.


Syntax: Int getcolor();
Getmaxcolor();

Returns maximum color of value.


Syntax: int getmaxcolor()

Getmaxcolor() returns the highest valid color value that can be passed to setcolor
for the current graphics driver and mode.

Setbkcolor(): setbkcolor() sets the current back ground color.


Syntax: setbkcolor(int color);

Setbkcolor sets the background to the color specified by color.

Getbkcolor(): returns the current back ground color.


Syntax: int getbkcolor();
Getbkcolor returns the current back ground color.

Circle(): This draws a circle.

Syntax: circle(int x, int y, int radius);


Circle draws a circle in the current drawing color
(x,y) center point of circle.
Radius: radius of circle

Arc() draws a circle arc


Syntax: arc( int x., int y, int stangle, int endangle, int radius);
Arc draws a circular arc in the current drawing color.
(x,y)---------------- center point of arc.
stangle------------- start angle in degrees.
endangle-----------end angle in degrees.
radius---------------radius of arc.

Pieslice(): pieslice() draws and fills a curcular pie slice.


Syntax: pieslice(int x, int y, int stangle, int endangle, radius);

130
Compiled By Getinet
2010

Pieslice() draws a pieslice in the current drawing color, then fills the current fill pattern and
fill color.

(x,y)-------------------center point of a pieslice.


Stangle----------------start angle in degrees.
Endangle--------------end angle in degrees.
Radius-----------------radius of arc, circle and pieslices.
The arc of a slice travels from stangle to endangle. If stangle=0 and endangle=360, the call
to arc draws a complete circle.

Angle for arc, circle and pieslices(counter-clockwise):

Getmaxx(): Returns maximum x screen coordinate.

Syntax: int getmaxx();

Getmaxx() returns the maximum value (screen relative) for the current graphics
driven and mode.

Getmaxy(): Returns maximum y value coordinate.

Syntax: int getmaxy();

Getmaxy() returns the maximum y value (screen relative) for the current graphics
driver and mode.

Example Program For Sample Graphics.

# include <stdio.h>
# include <conio.h>
# include <graphics.h>

131
Compiled By Getinet
2010

# include <stdlib.h>
void main()
{
int gm,gd,ec,grok;
gd=DETECT;
initgraph(&gd,&gm," ");
ec=graphresult();
if(ec != grok)
{
printf("GRAPHICS ERROR: %s\n",grapherrormsg(ec));
printf("ENTER ANY KEY TO HOLD");
getch();
exit(1);
}
printf("X VALUE :%d\n",getmaxx());
printf("Y VALUE :%d\n",getmaxy());
outtextxy(100,100,"WELCOME TO GRAPHICS");
getch();
closegraph();
}

Example Program For Displaying The Text In Graphics Format.

# include <conio.h>
# include <graphics.h>
void main()
{
int gd,gm,i;
gd=DETECT;
initgraph(&gd,&gm," ");
setcolor(GREEN);
setcolor(RED);
for(i=0;i<=4;i++)
{
cleardevice();
settextstyle(i,0,5);
outtextxy(50,50,"DASARI");
outtextxy(100,100,"SANDEEP KUMAR");
outtextxy(150,50,"SENIOR INTER");
getch();
}
closegraph();
}

Example Program For Displaying A Text In Corresponding Place Using Commands In


Program.

132
Compiled By Getinet
2010

# include <conio.h>
# include <graphics.h>
void main()
{
int gd,gm,i,x,y,c,center_text;
gd=DETECT;
initgraph(&gd,&gm," ");
x=getmaxx()/2;
y=getmaxy()/2;
for(x=25,i=0;i<250,i<5;i++)
{
if(c == getmaxcolor())
c=0;
setcolor(c);
arc(x,y,0,180,i);
}
setcolor(YELLOW);
settextstyle(4,0,5);
settextjustify(center_text,center_text);
outtextxy(x,y,"SANDEEP KUMAR");
getch();
closegraph();
}

set color(c);
setfillstyle(0,c);
pieslice(x,y,0,180,I);
delay(1000);
setfillstyle(1,RED);
pieslice(x,y,0,180,I);

Line():Draws a line between two specified points.

Syntax: line(int x1, int y1, int x2, int y2);


Line draws a line from (x1,y1) to (x2,y2) using the current color, line, style and
thickness.

Setlinestyle(): Sets the current line style and width or pattern.

Syntax: Setlinestyle(int linestyle, unsigned pattern, int thickness);

133
Compiled By Getinet
2010

Sets the style for all drives drawn by line, lineto, rectangle, drawpoly etc. You can
use the following line styles.

NAME VALUE MEANING

SOLID_LINE 0 Displays solid line.

DOTTED_LINE 1 Displays dotted line.

CENTER_LINE 2 Displays centered line.

DASHED_LINE 3 Displays dashed line.

USERBIT_LINE 4 Displays use defined line

Style.

Bar(): This function draws a bar.


Syntax: bar(int left, int top, int right, int bottom);

Bar() draws a filled in rectangular two dimensional bar. The bar is filled using the
current filled part and fill color bar() does not outline the bar. To draw an outlined two
dimensional bar else bar3d() with depth=0.

(left-top):- the rectangle upper left corner.

(right-bottom):- the rectangles lower right.

Setfillstyle(): sets the fill pattern and color.


Syntax: setfillstyle(int pattern, int color);
Setfillstyle() sets the current fill pattern and fill color.

FILL PATTERN-NAMES VALUE MEANS FILL WITH

EMPTY-FILL 0 Back ground color.


SOLID-FILL 1 Solid fill.
LINE-FILL 2
LTSLASH-FILL 3 //// this type of thin lines.
SLASH-FILL 4 thick lines.
BKSLASH-FILL 5 \\\\\\ thick lines.
LTBKSLASH-FILL 6 \\\\\\\\\\
HATCH-FILL 7 Light hatch.

134
Compiled By Getinet
2010

XHATCH-FILL 8 Heavy cross hatch.


INTERLEAVE-FILL 9 Interleaving lines.
WIDE-DOT-FILL 10 Widely spaced dots.
CLOSE-DOT-FILL 11 Closely spaced dots.
USER-FILL 12 User defined fill pattern.

All EMPTY-FILL fill with the current fill color. EMPTY-FILL uses the current
back ground color.

Bar3d(): This functions draws a 3-d bar.


Syntax: bar3d(int left, int top, int right, int bottom, int depth, int topflag);

Bar3d() draws a three dimensional rectangular bar, then fills it using the current fill
pattern. And fill color. The three dimensional outline of the bar is drawn in the current line
style and color.
Depth:Bars depth in pixels.
Topflag: Whether a three dimensional top is put on the bar or hot.
Left top: Rectangle upper left corner.
Right bottom: Rectangle lower right corner

If topflag is non zero a top is put on the bar. If top flag is 0, no top is put on the bar.
This makes it possible to stack serial bars on top of one another.

Rectangle(): This function draws a rectangle.


Syntax: rectangle(int left, int top, int right, int bottom);
Rectangle() draws a rectangle in the current line style, thickness and drawing color.
Left top is the upper left corner of the rectangle and right bottom is it is lower right corner.

Example Program For Drawing Bar Graph.

# include <stdio.h>
# include <conio.h>
# include <graphics.h>
# include <dos.h>
void main()
{
int gd,gm,i=0,x,y;
gd=DETECT;
initgraph(&gd,&gm," ");
x=getmaxx()/2;
y=getmaxy()/2;
for(i=0;i<13;i++)
{

135
Compiled By Getinet
2010

setcolor(RED);
setfillstyle(i,WHITE);
bar3d(x-100,y-100,x+100,y+100,30,1);
delay(1000);
}
closegraph();
}
Rand(): Random numbers generator.
Syntax: int rand();
Rand uses a multiplicative congenital random number generator with period 232 to
return to return successive pseudo random number in the range 0 to RAND-MAX.

Random(): Macro that returns an integer.


Syntax: int random(int num);
Random returns a random numbers between 0 and (num-1).
Imagesize(): Returns the number of bytes to require to store a bit image.
Syntax: int imagesize(int left, int top, int right, int bottom);

Imagesize() determines the size of the memory area required to store a BIT image.
Image size returns the size of required memory area in bytes use malloc() function to
allocate memory for the specified object.

Getimage(): Saves a bit image of the specified region into memory.


Syntax: Getimage(int left, int top, int right, int bottom, int y, bitmap);

Getimage() copies an image from the screen to memory left, top, right, bottom,
defines the screen area to which the rectangle is copied.

Putimage(): outputs a bit image to screen.


Syntax: Putimage(int left, int top, int *bitmap, int op);

Putimage() puts the bit image previous saved with setimage() back on the screen
with the upper left corner of the image placed at left, top. Bit map points to the area in
memory where the source image is stored. The op parameter to put image specifies a
combination operator that controls how the color function each destination pixel on screen
is computed based on the pixel on screen and the corresponding source pixel in memory.
You can use the following for op

VALUE DESCRIPTION
0 Copy
1 Exclusive OR
2 Inclusive OR
3 AND
4 Copy the inverse of the source.

Sound(): Sound turns the PC speakers on at the specified frequency.

136
Compiled By Getinet
2010

Syntax: sound(unsigned frequency);


Frequency specifies the frequency of the sound in hertz(cycles per seconds).

Nosound(): No sound turns the PC speakers off.


Syntax: Nosound()

No sound turns the speaker off after it has been turned on by a call to sound().

Restore crtmode(): Restores the character mode screen to its pre init graph settings.
Syntax: restorecrtmode();

Getgraphmode(): Returns the current graphics mode.


Syntax: Getgraphmode();
Your program must make a successful call to initgraph before calling
Getgraphmode().

Sector(): Sector draws and fills an elliptical pieslice.


Syntax: sector(int x, int y, int stangle, int endangle, int radius, int yradius);
Sector draws and fills and elliptical pieslice in the current drawing color then fills if
using the patterns and color defined by set fill style and set fill pattern.

Example Program For Drawing Lines, Circles And Lines Randomly On The Screen.

# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
# include <dos.h>
# include <graphics.h>
void main()
{
int gd,gm;
gd=DETECT;
initgraph(&gd,&gm," ");
clear device();
while(!kbhit())
{
setcolor(random(15));
line(random(640),random(50),random(640),random(50));
circle(random(640),random(480),random(50));
line(random(640),random(50),random(640),random(480));
delay(2);
}
closegraph();
}

Example Program For Drawing Our Indian Flag.

137
Compiled By Getinet
2010

# include <graphics.h>
# include <stdlib.h>
# include <conio.h>
void main()
{
int gd,gm;
gd=DETECT;
initgraph(&gd,&gm," ");
setfillstyle(1,RED);
bar(0,0,getmaxx(),100);
setfillstyle(1,WHITE);
bar(0,101,getmaxx(),200);
setfillstyle(1,GREEN);
bar(0,201,getmaxx(),300);
setcolor(BLACK);
circle(280,150,50);
line(230,150,330,150);
line(280,100,280,200);
line(245,113,316,187);
getch();
closegraph();
}

Example Program For Drawing Circles And Lines.

# include <graphics.h>
# include <stdlib.h>
# include <conio.h>
# include <dos.h>
void drawman()
{
circle(300,100,30);
circle(202,100,5);
circle(318,100,5);
line(300,130,300,200);
line(300,137,350,145);
line(300,137,250,145);
line(300,200,200,240);
line(300,200,320,240);
}
void main()
{
int gd,gm,col=1;
gd=DETECT;
initgraph(&gd,&gm," ");

138
Compiled By Getinet
2010

while(!kbhit())
{
setcolor(col);
drawman();
arc(290,110,180,0,4);
line(350,145,355,137);
line(250,145,255,137);
line(200,240,272,244);
line(320,240,320,244);
settextstyle(4,0,5);
outtextxy(50,300,"art by D.S.SANDEEP KUMAR");
sleep(3);
cleardevice();
drawman();
arc(250,110,0,180,4);
line(250,145,355,150);
line(250,145,255,150);
line(280,240,272,235);
line(320,240,320,235);
outtextxy(80,200,"DONT WORRY, BE HAPPY");
outtextxy(80,300,"art by SIMON PAL");
sleep(3);
cleardevice();
col++;
if(col>15)
col=1;
sound(random(600));
}
nosound();
closegraph();
}

Example Program For Drawing Indian Flag With Stand.

# include <graphics.h>
# include <stdlib.h>
# include <conio.h>
void main()
{
int gd,gm;
gd=DETECT;
initgraph(&gd,&gm," ");
setfillstyle(1,BLUE);
bar(100,100,105,300);
setfillstyle(1,RED);
bar(106,100,180,120);

139
Compiled By Getinet
2010

setfillstyle(1,LIGHTGRAY);
bar(106,121,180,141);
circle(144,131,10);
setfillstyle(1,GREEN);
bar(106,142,180,162);
setfillstyle(1,LIGHTBLUE);
bar(90,300,115,320);
setfillstyle(1,CYAN);
bar(80,321,125,341);
setfillstyle(1,BROWN);
bar(70,341,135,361);
outtextxy(150,50,"I LOVE INDIA");
getch();
closegraph();
}

Example Program For Drawing An Putpixel() And RANDOM FUNCTION.

# include <graphics.h>
# include <conio.h>

# include <stdlib.h>
void main()
{
int gd,gm;
clrscr();
gd=DETECT;
initgraph(&gd,&gm," ");
while(!kbhit())
putpixel(random(640),random(400),random(15));
closegraph();
}

Example Program From Drawing Charts.

# include <graphics.h>
# include <stdlib.h>
# include <stdio.h>
# include <conio.h>
void main()
{
int gd,gm,x1,y1,x2,y2,x3,y3,ch,n1,n2,n3;
float temp;
char tit[30];
gd=DETECT;
initgraph(&gd,&gm," ");

140
Compiled By Getinet
2010

printf("\nENTER FIRST VALUE FOR X-AXIS :");


scanf("%d",&x1);
printf("\nENTER SECOND VALUE FOR X-AXIS :");
scanf("%d",&x2);
printf("\nENTER THIRD VALUE FOR X-AXIS :");
scanf("%d",&x3);
printf("\nENTER FIRST VALUE FOR Y-AXIS :");
scanf("%d",&y1);
printf("\nENTER SECOND VALUE FOR Y-AXIS :");
scanf("%d",&y2);
printf("\nENTER THIRD VALUE FOR Y-AXIS :");
scanf("%d",&y3);
printf("\nENTER TITLE");
scanf("%s",tit);
ch=0;
while(ch<5)
{
cleardevice();
gotoxy(20,4);
printf("\n1.LINE GRAPH");
gotoxy(20,5);
printf("\n2.BAR GRAPH");
gotoxy(20,6);
printf("\n3.3D BAR GRAPH");
gotoxy(20,7);
printf("\n4.PIE GRAPH");
gotoxy(20,8);
printf("\n5.EXIT GRAPH");
gotoxy(20,10);
printf("\nENTER YOUR CHOICE\t");
scanf("%d",&ch);
cleardevice();
switch(ch)
{
case 1:
if(y1>=10000)
n1=y1/1000;
else
n1=y1/100;
if(y2>=10000)
n2=y2/1000;
else
n2=y2/100;
if(y3>=10000)
n3=y3/1000;
else

141
Compiled By Getinet
2010

n3=y3/100;
outtextxy(300,50,tit);
line(200,400,200,(300-x1));
setcolor(3);
circle(200,(300-x1),5);
setcolor(4);
line(200,(300-x1),220,(300-x2));
circle(220,(300-x2),5);
setcolor(2);
circle(240,(300-x3),5);
line(220,(300-x2),240,(300-x2));
getch();
break;
case 2:
if(y1>=10000)
n1=y1/1000;
else
n1=y1/100;
if(y2>=10000)
n2=y2/1000;
else
n2=y2/100;
if(y3>=10000)
n3=y3/1000;
else
n3=y3/100;
outtextxy(300,50,tit);
setfillstyle(1,4);
bar(200,400,220,(300-x1));
setfillstyle(1,7);
bar(221,400,241,(300-x2));
setfillstyle(1,2);
bar(242,400,262,(300-x3));
getch();
break;
case 3:
if(y1>=10000)
n1=y1/1000;
else
n1=y1/100;
if(y2>=10000)
n2=y2/1000;
else
n2=y2/100;
if(y3>=10000)
n3=y3/1000;

142
Compiled By Getinet
2010

else
n3=y3/100;
outtextxy(300,50,tit);
setfillstyle(1,4);
bar3d(200,400,220,(300-x1),60,1);
setfillstyle(1,7);
bar3d(221,400,241,(300-x2),60,1);
setfillstyle(1,2);
bar3d(242,400,262,(300-x3),60,1);
getch();
break;
case 4:
if(y1>=10000)
n1=y1/1000;
else
n1=y1/100;
if(y2>=10000)
n2=y2/1000;
else
n2=y2/100;
if(y3>=10000)
n3=y3/1000;
else
n3=y3/100;
outtextxy(300,50,tit);
temp=360.0/(x1+x2+x3);
n1=x1*temp;
n2=x2*temp;
n3=x3*temp;
setfillstyle(1,4);
pieslice(200,200,0,n1,200);
setfillstyle(1,7);
pieslice(200,200,n1,(n1+n2),200);
setfillstyle(1,2);
pieslice(200,200,(n1+n2),(n1+n2+n3),200);
getch();
break;
}
}
closegraph();
}

143

You might also like