Beruflich Dokumente
Kultur Dokumente
MAIN PROGRAM
FUNCTION 1 FUNCTION 2
FUNCTION 3
1
RELATION BETWEEN FUNCTION AND DATA IN THE
PROCEDURE ORIENTED PROGRAMMING.
system. It ties data more closely to the function that operate on it and
protects it from accidental modification from outside functions.
Object A object B
DATA DATA
FUNCTIONS FUNCTIONS
2
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.
POLYMORPHISM :
3
DYNAMIC BINDING :
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.
4
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 files consists of the entities (objects) related
to input and output.
Syntax : cout<<[message][variable]<<[message]
[variable]<<…….;
Syntax : cin>>variable>>variable…….
"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.
5
Syntax : // comment
# include <iostream.h>
# include <conio.h>
void main()
{
clrscr();
cout<<"***WELCOME TO C++ PROGRAMMING***";
cout<<"***THOMAS SUGUNAKAR RAJA***";
cout<<"***M C A***";
}
# 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();
}
# include <iostream.h>
# include <conio.h>
6
void main()
{
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').
7
# include <iostream.h>
# include <conio.h>
void main()
{
int n;
clrscr();
cout<<"ENTER A NUMBER "<<endl;
cin>>n;
for(i=1;i<=n;i++)
cout<<i<<"\t";
getch();
}
# include <iostream.h>
# include <stdio.h>
# include <conio.h>
void main()
{
int a,b,c,d,e,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();
}
8
REFERENCE VARIABLES :
# 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;
9
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();
}
10
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
11
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
type.
Program For Function Overloading Operation
# include <iostream.h>
# include <stdio.h>
# include <conio.h>
int add(int 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;
12
cout<<"FLOAT VALUES ARE :"<<f1<<"\t"<<f2<<endl;
cout<<"LONG VALUES ARE :"<<l1<<"\t"<<l2<<endl;
STRUCTURES
13
char ena[10];
};
struct employ emp;// C declaration
employ emp //C++ declaration
emp.eno,emp.ena,emp.bs,emp.da,
emp.hra,emp.pf
# 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;
cout<<"STUDENT'S NAME IS :"<<s.sna<<endl;
cout<<"COURSE NAME IS :"<<s.cr<<endl;
cout<<"TOTAL FEES IS :"<<s.tf<<endl;
14
cout<<"PAID FEES IS :"<<s.fp<<endl;
cout<<"DUE FEES IS :"<<due<<endl;
getch();
}
CLASSES
15
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 from 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 datatmembers 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
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);
16
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();
}
# include <iostream.h>
# include <stdio.h>
17
# include <conio.h>
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;
18
}
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;
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();
}
# 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()
19
{
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;
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();
20
st.output();
cout<<"TOTAL MARKS ARE :"<<tm<<endl;
cout<<"AVERAGE MARKS ARE :"<<am<<endl;
cout<<"RESULT OBTAINED :"<<res<<endl;
getch();
}
# include <iostream.h>
# include <stdio.h>
# include <conio.h>
class employ
{
int eno;
char ena[20],eg;
float bs;
public:
void accept()
{
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);
}
21
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;
break;
case 'C':
da=bsal*.13;
hra=bsal*.15;
pf=bsal*.006;
it=bsal*.005;
break;
}
clrscr();
gs=bsal+da+hra;
22
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();
}
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.
23
# 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()
24
{
sales s;
int units,rate,samt,comm,pcode;
clrscr();
s.input();
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 :
25
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.
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()
26
{
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();
for(i=0;i<5;i++)
{
cout<<"THE VALUES OF THE CELL :"<<i<<endl;
b[i].output();
getch();
}
}
FRIEND FUNCTIONSSDD
27
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.
# include <iostream.h>
# include <conio.h>
class sample;
class myclass
{
int a;
public:
28
void input()
{
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;
29
getch();
}
# include <iostream.h>
# include <stdio.h>
# include <conio.h>
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
{
30
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;
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();
}
31
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;
}
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;
}
32
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
class class_name
33
{
members;
public:
class_name(arguments) //constructor
{
statements;
}
};
E.g.:
class sample
{
private:
int a,b;
float x,y;
public:
sample() //constructor function
{
a=100;
b=200;
x=35.15;
y=564.25;
}
};
void main()
{
clrscr();
sample s;
getch();
}
34
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;
}
};
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();
35
}
# 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;
cout<<"fee paid is :"<<fp<<endl;
cout<<"due fee is :"<<due<<endl;
}
};
void main()
{
36
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();
}
# 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);
37
sales b=sales(101,"KIRAN",3000);
cout<<"VALUES OF T :"<<endl;
t.output();
cout<<"VALUES OF B :"<<endl;
b.output();
getch();
}
DESTRUCTORS:
OPERATOR OVERLAODING :
38
called operator function, which describes the task. The general
form of an operator function is:
return type operator op(argument list)
{
function_body();
}
# include <iostream.h>
# include <conio.h>
class exam
{
int a;
float b;
long c;
public:
exam() //constructor function
{
a=10;
b=25.65;
c=42500;
}
39
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();
}
40
# 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();
41
r=p+q; //function calling
cout<<"values of first object :"<<endl;
p.print();
cout<<"values of second object :"<<endl;
q.print();
cout<<"addition object values are :"<<endl;
r.print();
getch();
}
# 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);
}
42
};
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();
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 pointer 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
43
operators manipulate memory on the free store, these are also
known as free store operators.
44
qprint() or sales.print();
# 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();
}
# include <iostream.h>
# include <stdio.h>
# include <conio.h>
class st
{
int sno, m1, m2, m3;
45
char sna[20];
public:
void accept()
{
cout<<"ENTER STUDENT NUMBER:";
cin>>sno;
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);
46
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
# include <iostream.h>
# include <conio.h>
47
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();
}
# include <iostream.h>
# include <stdio.h>
# include <conio.h>
template<class A,class B>
A add (A x,B y)
{
return(x+y);
}
48
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
{
A n,m,f;
public:
void input()
{
cout<<"ENTER FIRST VALUE :";
cin>>n;
cout<<"ENTER SECOND VALUE :";
cin>>m;
49
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();
50
}
INHERITANCE (REUSABILITY)
A A B
B C
B
B C D
C
5.Hybrid Inheritance.
B C
51
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 sent 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.
52
{
- -------
- - - - - - - - //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 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 becomes 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
53
{
- - - - - - //members of class B
- - - - - -
- - - - - -
- - - - - -
};
# include <iostream.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()
{
cout<<"ENTER TWO INTEGERS :";
cin>>m,n;
}
void display()
{
cout<<"M VALUE IS :"<<m<<endl;
cout<<"N VALUE IS :"<<n<<endl;
54
}
};
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();
}
# 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;
55
cout<<"STUENT'S NAME IS "<<sna<<endl;
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;
56
}
void resout()
{
tm=mm+mp+mc;
am=tm/3;
if(am>75)
strcpy(res,"DISTINCTION");
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();
}
57
MULTIPLE INHERITANCE.
PROTECTED MEMBERS.
58
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
{
- - - - - - //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
- - - - - -
};
# include <iostream.h>
# include <conio.h>
class employ
59
{
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 :";
60
cin>>pf;
cout<<"ENTER INCOME TAX :";
cin>>it;
}
};
class salary:public employ,public allow,public
ded
{
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();
61
s.dedinput();
clrscr();
s.calc_sal();
s.output();
getch();
}
HIERARCHICAL INHERITANCE.
# 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;
}
62
};
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:
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;
}
};
63
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 :";
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;
64
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();
}
# include <iostream.h>
# include <stdio.h>
# include <conio.h>
# include <string.h>
class student
{
65
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;
}
};
66
class result:public test, public sports
{
int tot,avg;
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
67
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();
}
68
Class A
{
-----
};
class b1 : virtual public A
{
-------
};
class b2 : public virtual A
{
------
};
class C : public b1, public b2
{
---- //only one copy of A will be inherited
};
VIRTUAL FUNCTIONS
69
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
70
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 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
}
71
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.
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:
72
ifstream fp1("sales.dat"); //open sales.dat file in input
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
73
close Function.
eof() Function.
Syntax: stream_object.eof();
fp.eof();
(Flwristu.cpp)
# include <iostream.h>
# include <conio.h>
# include <fstream.h>
class stud
{
int sno,tm;
char sna[20];
public:
void input()
{
cout<<"ENTER STUDENT NUMBER ";
cin>>sno;
cout<<"ENTER STUDENT NAME ";
cin>>sna;
74
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();
}
75
{
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();
}
# 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;
}
};
76
void main()
{
char ch='y';
empl e;
ofstream fp("employ.dat");
while(ch=='y' || ch=='Y')
{
clrscr();
e.input();
fp.write((char *)&e,sizeof(e));
cout<<"DO YOU WANT TO ENTER ONE MORE RECORD
Y/N ";
cin>>ch;
}
fp.close();
}
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()
77
{
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')
{
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;
78
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();
}
Stream_object.open("filename", mode);
79
ios::out for ofstream functions meaning open for
writing only.
Parameter Meaning
80
3. The mode can combine two or more parameters using
the "|" symbol.
81
6. You may attempt to perform an operation when the
file is not opened for that purpose.
82
from any other error reported
and continue operation.
83
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();
}
84
{
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();
}
85
float cbal;
public:
void output()
{
cout<<"ACCOUNT HOLDER NUMBER "<<acno<<endl;
cout<<"ACCOUNT HOLDER NAME "<<name<<endl;
cout<<"ACCOUNT HOLDER BALANCE "<<cbal<<endl;
}
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();
}
86
RANDOM ACCESSING FILE FUNCTIONS.
Syntax: seekg(offset,
ref_position);
seekp(offset,
ref_position);
87
Seek call Action
Syntax: stream_object.tellp();
stream_object.tellg();
88
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()
{
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;
}
89
}
90
}
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())
{
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);
91
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();
remove("employ.dat");
rename("temp.dat","employ.dat");
if(s>0)
cout<<"RECORD DELETED SUCCESSFULLY
"<<teno<<endl;
else
cout<<"RECORD NOT FOUND "<<teno<<endl;
92
}
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();
}
93
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();
94
}
break;
case 2:
clrscr();
fp.open("employ.dat",ios::in);
if(fp.bad())
{
cout<<"FILE NOT FOUND "<<endl;
getch();
fp.close();
}
else
{
cout<<"\t\t"<<"EMPLOY LIST"<<endl;
cout<<"ENO"<<"\t\t"<<"EMAME"<<"\t\t"<<"BASIC"<<e
ndl;
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
95
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:
BANK OF INDIA
HYDERABAD
PAY SLIP FOR THE MONTH OF:
LOAN AMOUNT
TOTAL ALLOWANCES:
TOTAL DEDUCTIONS:
GROSS SALARY:
NET SALARY:
96
1. If Loan Is There In Loan.Dat, Calculate The Loan Amount
As Per The Following Formula
Loan Amount = Amt Taken /No Of 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 ";
cin>>eadd;
cout<<"ENTER EMPLOY DESIGNATION";
cin>>desg;
cout<<"ENTER EMPLOYE JOINDATE ";
cin>>jd;
}
};
class salary
{
char desg[10];
97
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;
}
};
void main()
{
employ emp;
98
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();
}
99
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>
# 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; }
100
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; }
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);
101
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;
}
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));
}
102
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);
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();
103
gotoxy(5,13);
cout<<bs<<"\t"<<hra<<"\t"<<da<<"\t"<<pf<<"\t"<<i
t<<"\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.
104
{
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)
105
{
clrscr();
box(9,20,17,50);
gotoxy(25,11);
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)
106
{
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();
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();
}
}
107
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
108
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;
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);
109
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");
strcpy(sopt[3],"RETURN TO MAIN");
row=11;
i=1;
int flag=1;
while(flag)
{
clrscr();
box(9,45,15,70);
gotoxy(50,11);
110
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);
gotoxy(15,10);
cout<<"ACCOUNT HOLDER NUMBER ";
cin>>acno;
111
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;
}
112
};
# include "my.h"
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);
113
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++;
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;
114
}
}
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;
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;
115
}
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));
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:
116
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
117
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
ORNAMENT CODE:
ORNAMENT NAME:
WEIGHT:
CURRENT MARKET RATE: (per gram)
NUMBER OF ITEMS:
BILLED AMOUNT:
118
# include <conio.h>
# include <fstream.h>
class ornament
{
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 ";
119
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()
{
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);
120
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();
}
121
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;
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);
122
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);
fp.read((char *)&cust,sizeof(cust));
while(!fp.eof())
{
fp1.open("ornament.dat",ios::in);
123
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();
124
}
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.
# 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();
125
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);
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;
126
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();
}
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)
{
127
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.
128
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.
129
Note that argv[0] always represents the command name
that invokes the program.
# 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
{
clrscr();
cout<<"TOTAL ARGUMENTS :"<<argc<<endl;
for(int i=0;i<argc;i++)
cout<<"THE ARGUMENT "<<"IS"<<argv[i]<<endl;
}
getch();
}
# include <iostream.h>
# include <conio.h>
# include <process.h>
# include <io.h>
130
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;
}
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
};
131
find first() //<dir.h>
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 ( ?, *).
CONSTANT DESCRIPTION
FA_DIREC Directory
FA_ARCH Archive
FINDNEXT(): <DIR.H>
Findnext() continue the search for files.
132
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.
Dflcurdi.cpp
LIBRARY MENU
133
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.
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.
X Y
134
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;
};
The first member is integer a and the second a pointer to the next
address in the list as shown below.
Test
A P
135
struct link x,y;
xnext=&y;
xnext=sno;
x=xnext;
xsno;
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
Printf("%d",x.nextsno);
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.
136
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.
# 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;
new1->next=NULL;
if(root==NULL)
root=new1;
else
prev->next=new1;
prev=new1;
scanf("%d",&temp);
printf("%d\n",temp);
}
137
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;
}
}
138
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();
139
while(strchr("cCiIdDqQ",c)==NULL);
printf("%c\n",c);
switch(c)
{
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
{
140
printf("The linked list after deletion
is \n");
display(root);
}
break;
case 'q':
case 'Q':
quit=1;
}
}while(!quit);
printf("\n");
}
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.
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.
141
# 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;
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;
142
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))
{
new_node->next=*start;
if(*start!=NULL)
(*start)->back=new_node;
*start=new_node;
new_node->back=NULL;
}
else
{
temp=*start;
143
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))
{
temp=temp->next;
++i;
}
if(temp->next!=NULL)
144
{
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 ");
145
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");
}
146
CIRCULAR LINKED LIST.
147
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
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;
}
148
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;
(*last)->next=*start;
}
else
*start=*last=NULL;
}
else
{
temp=*start;
i=2;
while((temp->next!=NULL) && (i<posn))
{
temp=temp->next;
++i;
149
}
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':
case 'C':
root=create(&last);
printf("\n The Created linked list is ");
display(root,last);
break;
case 'i':
case 'I':
150
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");
}
151
QUEUES AND STACKS.
152
# 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;
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;
153
}
}
}
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");
for(i=q.f;i<=q.r;i++)
printf("%d\t",q.item[i]);
}
154
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--;
}
155
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;
{
if(str!=NULL)
{
ind(str->lptr);
printf("%i",str->val);
156
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();
157
do
{
printf("How Many Elements :");
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)
158
{
temp=(struct node*)malloc(sizeof(struct
node));
if(c<prev->val)
prev->lptr=temp;
else
prev->rptr=temp;
}
}
if(!ef)
{
temp->val=c;
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
159
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;
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);
160
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
{
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();
161
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.
162
*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).
163
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().
164
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
LITGHT CYAN 11
LIGHT RED 12
LIGHT MAGENTA 13
YELLOW 14
WHITE 15
165
Setbkcolor sets the background to the color specified by color.
Pieslice() draws a pieslice in the current drawing color, then fills the
current fill pattern and fill color.
166
Getmaxx(): Returns maximum x screen coordinate.
# include <stdio.h>
# include <conio.h>
# include <graphics.h>
# include <stdlib.h>
void main()
{
int gm,gd,ec,grok;
gd=DETECT;
initgraph(&gd,&gm," ");
167
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();
}
# 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();
}
168
Example Program For Displaying A Text In Corresponding Place
Using Commands In Program.
# 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);
169
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.
Style.
170
(right-bottom):- the rectangles lower right.
171
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.
# 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++)
{
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();
172
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.
VALUE DESCRIPTION
0 Copy
1 Exclusive OR
173
2 Inclusive OR
3 AND
4 Copy the inverse of the
source.
No sound turns the speaker off after it has been turned on by a call
to sound().
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
# include <dos.h>
174
# 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();
}
# 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);
175
line(245,113,316,187);
getch();
closegraph();
}
# 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," ");
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();
176
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();
}
177
setfillstyle(1,CYAN);
bar(80,321,125,341);
setfillstyle(1,BROWN);
bar(70,341,135,361);
outtextxy(150,50,"I LOVE INDIA");
getch();
closegraph();
}
# 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();
}
# 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;
178
initgraph(&gd,&gm," ");
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;
179
if(y2>=10000)
n2=y2/1000;
else
n2=y2/100;
if(y3>=10000)
n3=y3/1000;
else
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));
180
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;
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;
181
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();
}
182