C++ Notes
C++ Notes
2010
C++
MAIN PROGRAM
FUNCTION 1 FUNCTION 2
FUNCTION 3
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.
1
Compiled By Getinet
2010
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.
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.
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 :
C++
<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
# 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();
}
# 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();
}
# 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:
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.
6
Compiled By Getinet
2010
int &c=b;
c=25;
# 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.
7
Compiled By Getinet
2010
add (10,20);
add (10);
add (); does not work, because there is no default value for argument x.
# 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.
# include <iostream.h>
# include <stdio.h>
# include <conio.h>
int add(int a,int b) { return(a+b); }
8
Compiled By Getinet
2010
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;
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
# 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
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.
The class declaration describes the type and scope of its members. The class
function definitions describe how the class functions are implemented.
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);
# 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
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
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
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();
}
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
# 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.
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.
# include <iostream.h>
# include <conio.h>
class sample;
class myclass
{
int a;
public:
void input()
{
21
Compiled By Getinet
2010
# 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();
}
# 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
25
Compiled By Getinet
2010
# 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();
}
# 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
# 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 :
# 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();
}
30
Compiled By Getinet
2010
# 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();
}
# 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
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.
sales s;
sales *q;
q =&s;
33
Compiled By Getinet
2010
qinput() or sales.input();
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;
char sna[20];
public:
void accept()
{
cout<<"ENTER STUDENT NUMBER:";
cin>>sno;
34
Compiled By Getinet
2010
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.
# 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
# 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();
}
# 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:
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
- - - - - -
- - - - - -
- - - - - -
};
# 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
# 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
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.
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
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
VIRTUAL FUNCTIONS
INLINE FUNCTIONS
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 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
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();
}
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();
}
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.
The file mode parameter can take one of such constants defined in the class "ios".
Parameter Meaning
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.
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).
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();
}
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();
}
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();
}
By using seekg( ) and seekp( ) functions, you can access the records randomly.
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.
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();
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;
}
}
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<<"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:
BANK OF INDIA
HYDERABAD
PAY SLIP FOR THE MONTH OF:
72
Compiled By Getinet
2010
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
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
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.
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
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;
}
};
# 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
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
ORNAMENT CODE:
ORNAMENT NAME:
WEIGHT:
CURRENT MARKET RATE: (per gram)
NUMBER OF ITEMS:
BILLED AMOUNT:
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).
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();
}
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.
# 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
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.
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.
# 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.
101
Compiled By Getinet
2010
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>
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_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.
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
LIBRARY MENU
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 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.
X Y
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
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;
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
105
Compiled By Getinet
2010
Printf("%d",x.nextsno);
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.
# 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
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.
# 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");
}
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.
# 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]);
}
# 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--;
}
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.
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
*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).
Graph error message returns a pointer to the error message string associated with
error code, the value returned by graph result.
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().
128
Compiled By Getinet
2010
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
Getmaxcolor() returns the highest valid color value that can be passed to setcolor
for the current graphics driver and mode.
130
Compiled By Getinet
2010
Pieslice() draws a pieslice in the current drawing color, then fills the current fill pattern and
fill color.
Getmaxx() returns the maximum value (screen relative) for the current graphics
driven and mode.
Getmaxy() returns the maximum y value (screen relative) for the current graphics
driver and mode.
# 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();
}
# 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();
}
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);
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.
Style.
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.
134
Compiled By Getinet
2010
All EMPTY-FILL fill with the current fill color. EMPTY-FILL uses the current
back ground color.
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.
# 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.
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() copies an image from the screen to memory left, top, right, bottom,
defines the screen area to which the rectangle is copied.
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.
136
Compiled By Getinet
2010
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();
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();
}
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();
}
# 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();
}
# 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();
}
# 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;
initgraph(&gd,&gm," ");
140
Compiled By Getinet
2010
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