0% found this document useful (0 votes)
70 views75 pages

Recordprograms 2

The program allows the user to search a library database by book number, name, author, or price range. It defines a Book class with private data members for book details and accessor functions to return the values. The main function inputs book details into an array of Book objects, takes the user's search criteria, and displays any books matching the search.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views75 pages

Recordprograms 2

The program allows the user to search a library database by book number, name, author, or price range. It defines a Book class with private data members for book details and accessor functions to return the values. The main function inputs book details into an array of Book objects, takes the user's search criteria, and displays any books matching the search.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

PLEASE ARRANGE THE PROGRAM ,OUTPUT[SEPARATE THEM FROM

WRITTEN WORK ] AND THEN TAKE THE PRINTOUT


1.Function overloading-Area calculation
2Classes and objects – Electricity bill
3Accessor functions-Library details
4Telephone bill – Nested classes
5Constructor Overloading-Interest calculation
6Inheritance –Employee Detail
7Text File creation and manipulation
8Payroll Processing-Binary file Processing
9Binary File Manipulation-Search
10 Binary File Processing –Searching and copying it in another file
11Binary Search –Array
12Linear Search – Array
13 Selection sort and Binary Search - Array
14 Bubble sort-structure
15 Merge sort
16 Linked stack
17 Reversing a string(stack as an array)
18 Hexadecimal Conversion(Linked stack)
19 Linked Queue
20 Circular Queue(as an array)
21 Distance calculation – Passing Objects as arguments
22 Reversing the elements in an array
23 Two Dimensional array formation
24 Middle row and middle column element in an array
25 Rotation Factor – Array
26 STRUCTURED QUERY LANGUAGE - This is sent as a separate file

Program 1 Function overloading-Area calculation

PROGRAM DEFINITION
To write a C++ program to calculate the area of different geometrical figures using
function overloading.
PROGRAM ANALYSIS
The function area() is overloaded to calculate the area of different geometrical figures such as
triangle , rectangle and square.
● float area(float a,float b, float c);
This function calculates the area of a triangle whose 3 sides are passed as parameters to
the function using the formula
s=(a+b+c)/2
ar =sqrt(s*(s-a)*(s-b)*(s-c))
● float area(float a, float b);
This function takes two arguments as length and breadth and calculates the area of a rectangle
using the formula a*b
● float area(float a);
This function takes single argument as side and calculate the area of the square using the
formula a*a
void main() – This function displays the menu and based on the choice from the user the
functions are executed. The function call statements are
ar=area(s1,s2,s3); //Area of a triangle
ar=area(s1,s2); //Area of a rectangle
ar=area(s1); //Area of a square

PROGRAM CODING
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
float area(float a,float b,float c)
{
float s,ar;
s=(a+b+c)/2;
ar=sqrt(s*(s-a)*(s-b)*(s-c));
return ar;
}
float area(float a,float b)
{
return a*b;
}
float area(float a)
{
return a*a;
}
void main()
{
clrscr();
int choice,s1,s2,s3,ar;
do
{
cout<<"\n Area Main menu \n";
cout<<"1.Triangle \n";
cout<<"2.Square \n";
cout<<"3.Rectangle \n";
cout<<"4.Exit \n";
cout<<"Enter your choice(1-4):";
cin>>choice;
cout<<"\n";
switch(choice)
{
case 1:cout<<"Enter 3 sides\n";
cin>>s1>>s2>>s3;
ar=area(s1,s2,s3);
cout<<"The area is"<<ar<<"\n";
break;
case 2:cout<<"Enter a side\n";
cin>>s1;
ar=area(s1);
cout<<"The area is"<<ar<<"\n";
break;
case 3:cout<<"Enter length & breadth\n";
cin>>s1>>s2;
ar=area(s1,s2);
cout<<"The area is"<<ar<<"\n";
break;
case 4:break;
default:cout<<"Wrong Choice!! \n";
};
}
while(choice>0&&choice<4);
getch();
}
OUTPUT:
Area Main Menu
1. Triangle
2. Square
3. Rectangle
4. Exit
Enter your choice(1-4): 3

Enter length & breadth


12 3
The area is 36

RESULT
The C++ program to calculate area of different geometrical shapes using function
overloading is executed successfully.

Program​ 2 classes and objects- Electricity Bill


PROGRAM DEFINITION
To write a C++ program to prepare electricity bill using classes.
PROGRAM ANALYSIS
● class bill
A class bill is declared with the following data members- customer name, house no, street name,
city, number of units consumed, the total cost.
The member functions inside this class are defined as void input() which receives the input from
the user.
The member function void call() which calculates the total amount based on the units
consumption.
If units<=200 cost = units * 2.5
else if units <=300 cost = (units-200)*3.5+500
else cost= 1150+(units-400*4)
The member function void output() displays the entire details about the customer including the
bill amount to be paid.
PROGRAM CODING
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class bill
{
char name[20], city[20], street[30];
int units, houseno;
float charge;
public:
void input()
{
cout<<"\nEnter the name of the customer: ";
cin>>name;
cout<<"Enter the house number of the customer: ";
cin>>houseno;
cout<<"Enter the city of the customer: ";
cin>>city;
cout<<"Enter the street of the customer: ";
cin>>street;
cout<<"Enter the number of units consumed: ";
cin>>units;
calc();
}
void calc()
{
if(units<=200)
charge=units*2.5;
else if(units<=300)
charge=((units-200)*3.0+500);
else if(units<=400)
charge=((units-300)*3.5+800);
else
charge=((units-400)*4.0+1150);
}
void output()
{
cout<<"\nName: "<<name;
cout<<"\nHouse number: "<<houseno;
cout<<"\nCity: "<<city;
cout<<"\nStreet: "<<street;
cout<<"\n\nTotal units: "<<units;
cout<<"\nTotal charges: "<<charge;
}
};
void main()
{
clrscr();
bill x[30];
int n, i;
cout<<"\n\t----------------ELECTRICITY BILL----------------\n";
cout<<"\nEnter the number of customers: ";
cin>>n;
for(i=0; i<n; i++)
{
cout<<"\nEnter the details of customer "<<i+1<<"\n";
x[i].input();
}
for(i=0;i<n;i++)
{
cout<<"\n\t\t\tELECTRICITY BILL"; ";
cout<<"\n\t\t\t~~~~~~~~~~~~~~~~\n";
cout<<"The bill for customer "<<i+1<<" is:\n";
x[i].output();
}
getch();
}
OUTPUT
----------------ELECTRICITY BILL----------------

Enter the number of customers: 2

Enter the details of customer 1

Enter the name of the customer: ADITHYA


Enter the house number of the customer: 21
Enter the city of the customer: chennai
Enter the street of the customer: valasaravakkam
Enter the number of units consumed: 340

Enter the details of customer 2

Enter the name of the customer: RESHWANTH


Enter the house number of the customer: 22
Enter the city of the customer: chennai
Enter the street of the customer: tnagar
Enter the number of units consumed: 200

ELECTRICITY BILL
~~~~~~~~~~~~~~~~
The bill for customer 1 is:

Name: ADITHYA
House number: 21
City: chennai
Street: valasaravakkam

Total units: 340


Total charges: 940
ELECTRICITY BILL
~~~~~~~~~~~~~~~~
The bill for customer 2 is:

Name: RESHWANTH
House number: 22
City: chennai
Street: tnagar

Total units: 200


Total charges: 500

RESULT
The C++ program to calculate electricity bill for the customers using class is executed
successfully.
PROGRAM 3​ ​ACCESSOR FUNCTIONS –BOOK DETAILS
PROGRAM DEFINITION
To write a C++ program using accessor functions to display the details of the books.
PROGRAM ANALYSIS
class book
This class contains private data members such as bkno, name, author, price.
void input()
This public member function gets the details of the books from the user.
Accessor functions:
int retbkno();

This function returns the book number which is a private data number.

char* retname();

This function returns the book name (string private data member)
strcmp() function is used to compare strings.

float retprice();
This function returns the price of the book(floating point data member)

char* retaut();
This function returns the author (string – private data member)
void disp();
This function displays the details of the book which is searched.
void main()
This function display the choices and accepts the search criteria from the user and performs
the search accordingly.
PROGRAM CODING
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class book
{
int bkno;
char name[30],author[30];
float price;
public:
void input();
int retbkno();
char* retname();
float retprice();
char* retaut();
void disp();
};

void book::input()
{
cout<<"Enter book no: ";
cin>>bkno;
cout<<"\nEnter book name: ";
gets(name);
cout<<"\nEnter author name: ";
gets(author);
cout<<"\nEnter price: ";
cin>>price;
}
int book::retbkno()
{
return bkno;
}
char* book::retname()
{
return name;
}
char* book::retaut()
{
return author;
}

float book::retprice()
{
return price;
}
void book::disp()
{
cout<<"\nBook no: "<<bkno<<"\nName :";
puts(name);
cout<<"Author: ";
puts(author);
cout<<"Price: "<<price;
}
void main()
{
clrscr();
book b[10];
int n,i,ch,flag=0;
int seano,primax,primin;
char seaname[30],seaaut[30];
cout<<"Enter no. of books: ";
cin>>n;
cout<<"\nEnter the details:";
for(i=0;i<n;i++)
{
cout<<"\nBook no."<<i+1<<"\n";
b[i].input();
}
cout<<"What do you want to search with:\n"<<"1.Book no.\n"<<"2.Book name\n"<<"3.Author
name\n"<<"4.Price Range\n"<<"Enter your choice: ";
cin>>ch;
switch(ch)
{
case 1:cout<<"Enter book no.";
cin>>seano;
for(i=0;i<n;i++)
{
if(b[i].retbkno()==seano)
{
b[i].disp();
flag=1;
}
}
break;

case 2:cout<<"Enter book name: ";


gets(seaname);
for(i=0;i<n;i++)
{
if((strcmp(b[i].retname(),seaname)==0))
{
b[i].disp();
flag=1;
}
}
break;

case 3:cout<<"Enter author name: ";


gets(seaaut);
for(i=0;i<n;i++)
{
if((strcmp(b[i].retaut(),seaaut)==0))
{
b[i].disp();
flag=1;
}
}
break;

case 4:cout<<"Enter maximum price: ";


cin>>primax;
cout<<"\nEnter minimum price: ";
cin>>primin;
for(i=0;i<n;i++)
{

if((b[i].retprice()<=primax)&&(b[i].retprice()>=primin))
{
b[i].disp();
flag=1;
}
}
break;
default :cout<<"WRONG CHOICE";
flag=1;
}
if(!flag)
{
cout<<"No books in the search criteria were found";
}
getch();}

INPUT AND OUTPUT


Enter no. of books: 3
Enter the details:
Book no.1
Enter book no: 101
Enter book name: c++
Enter author name: sumita
Enter price: 500
Book no.2
Enter book no: 102
Enter book name: c#
Enter author name: balaguru
Enter price: 700
Book no.3
Enter book no: 103
Enter book name: samy
Enter author name: sami
Enter price: 800
What do you want to search with:
1.Book no.
2.Book name
3.Author name
4.Price Range
Enter your choice: 1
Enter book no.102
Book no: 102
Name :c#
Author: balaguru
Price: 700

Program 4 Nested class​-​Telephone Bill


PROGRAM DEFINITION
To write a C++ program using nested class to prepare telephone bill for customers.
PROGRAM ANALYSIS
class addr
A class addr is defined with the data members – block, street, city and the member functions
input() to receive the values from the user and the function output() to display the values.
class telephonebill
Another class telephonebill is defined with name, phoneno, calls, rent, charge, subtotal,
subcharge and total. The rental amount is assigned to 500. The object address for the class addr
is created inside this class. The input() function inside this class is used to get the details. The
object address.input() will invoke the function input of addr class.(Nested class).
void calcbill()
The function calcbill() calculates the total amount to be paid by calculating
If(calls<=150) then the charge = 0.0
else if(calls<=300)charge=(calls-150)*1.0
else if(calls <=450)charge=150+(calls-450)*1.5
else charge= 375+(calls-450)*2.0 subcharge=0.2*charge
total = rent+charge+subcharge
void output()
The output() function displays the name,phoneno,calls made, address and the total amount.

PROGRAM CODING
TELEPHONE BILL – NESTED CLASS
//Telephone Bill
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class addr
{
int block;
char street[30], city[20];
public:
void input()
{
cout<<"Enter the address:\n";
cout<<"Enter the block number: ";
cin>>block;
cout<<"Enter the street: ";
gets(street);
cout<<"Enter the city: ";
gets(city);
}
void output()
{
cout<<"\nAddress: ";
cout<<block<<", "<<street<<", "<<city;
}
};
class telephonebill
{
char name[30];
addr address;
long phoneno;
int calls, rent;
float charge, surcharge, total, subtotal;
public:
telephonebill()
{ rent=500; }
void input()
{
cout<<"\nEnter the name: ";
gets(name);
cout<<"Enter the phone number: ";
cin>>phoneno;
address.input();
cout<<"Enter the number of calls: ";
cin>>calls;
calcbill();
}
void calcbill()
{
charge=0.0;
if(calls<=150)
charge=0.0;
else if(calls<=300)
charge=(calls-150)*1.0;
else if(calls<=450)
charge=150+((calls-300)*1.5);
else
charge=375+((calls-450)*2.0);
surcharge=0.2*charge;
total=rent+surcharge+charge;
}
void output()
{
cout<<"\nName: "<<name;
cout<<"\nPhone number: "<<phoneno;
cout<<"\nNumber of calls: "<<calls;
address.output();
cout<<"\nBill: "<<total;
}
};
void main()
{
clrscr();
int n, i;
telephonebill t[20];
cout<<"\n\t----------------TELEPHONE BILL----------------\n";
cout<<"\nEnter the number of customers: ";
cin>>n;
for(i=0;i<n;i++)
{ cout<<"\nEnter the details of customer "<<i+1<<":";
t[i].input();
}
for(i=0;i<n;i++)
{ cout<<"\n\t\t\tTELEPHONE BILL";
cout<<"\n\t\t\t**************";
cout<<"\nCustomer "<<i+1<<":";

t[i].output();
}
getch();
}
INPUT AND OUTPUT

----------------TELEPHONE BILL----------------
Enter the number of customers: 1

Enter the details of customer 1:


Enter the name: sridharan
Enter the phone number: 8098412222
Enter the address:
Enter the block number: 12
Enter the street: kamaraj
Enter the city: chennai
Enter the number of calls: 456

TELEPHONE BILL
**************
Customer 1:
Name: sridharan
Phone number: -491522370
Number of calls: 456
Address: 12, kamaraj, chennai
Bill: 964.400024

RESULT:
The C++ program to prepare telephone bill using nested class is executed successfully.

PROGRAM 5​ ​CONSTRUCTOR OVERLOADING- DEPOSIT INTEREST


CALCULATION

PROGRAM DEFINITION
To write a C++ program to calculate the interest for the deposit amount using the
Constructor Overloading.

PROGRAM ANALYSIS
class Deposit
This class contains the following private data members – principal, time, rate and
total_amt.
​Constructor Overloading
Deposit();
This is the default constructor which initializes the value of the principal, time and rate as 0.0.
Deposit(long,int,float)
This is a parameterized constructor which initializes the value of principal ,time and rate as
2000,2,0.07f
Deposit(long,int)
This is a parameterized constructor which initializes the value of principal and time as 4000,1
Deposit(long,float)
This is a parameterized constructor which initializes the value of principal and rate as 3000,
0.12f
void deposit ::calc_amt()
A function to calculate the total _amt using principal+(principal*time *rate)/100
void deposit::display()
A function to display principal ,time,rate,total_amt
void main()
Creating objects for class Deposit D1,D2,D3, D4 and calculates total_amt of interest
respectively.

PROGRAM CODING
//Constructor overloading
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class Deposit
{
long int principal;
int time;
float rate;
float amt;
public:
Deposit();
Deposit(long p, int t, float r);
Deposit(long p, int t);
Deposit(long p, float r);
void calc_amt(void);
void display(void);
};
Deposit::Deposit()
{
Principal=time=rate=0.0;
}
Deposit::Deposit(long p, int t, float r)
{
principal= p;
time=t;
rate=r;
}
Deposit::Deposit(long p, int t)
{
principal=p;
time=t;
rate=0.08;
}
Deposit::Deposit(long p, float r)
{
principal=p;
time=2;
rate=r;
}
void Deposit::calc_amt()
{
amt=principal+(principal*time*rate)/100;
}
void Deposit::display()
{
cout<<”\nPrincipal Amount:Rs.”<<principal;
cout<<”\tPeriod of investment:”<<time<<”years”;
cout<<”\nRate of Interest:”<<rate;
cout<<”\tTotal Amount:Rs.”<<amt<<”\n”;
}
void main()
{
clrscr();
Deposit D1,D2(2000,2,0.07f),D3(4000,1),D4(3000,0.12f);
D1.calc_amt();
D2.calc_amt();
D3.calc_amt();
D4.calc_amt();
cout<<”Object 1\n”;D1.display();
cout<<”Object 2\n”;D2.display();
cout<<”Object 3\n”;D3.display();
cout<<”Object 4\n”;D4.display();
getch();
}
OUTPUT:
Object 1
Principal Amount: Rs.0 Principal Investment :0years
Rate Of Interest :0 Total Amount:Rs.0
Object 2
Principal Amount: Rs.2000 Principal Investment :2years
Rate Of Interest :0.07 Total Amount:Rs.2280
Object 3
Principal Amount: Rs.4000 Principal Investment :1years
Rate Of Interest :0.08 Total Amount:Rs.4320
Object 4
Principal Amount: Rs.3000 Principal Investment :2years
Rate Of Interest :0.12 Total Amount:Rs.3720

RESULT:
Thus the program to calculate interest for the amount deposited using constructor overloading is
executed

PROGRAM 6 ​ ​INHERITANCE-EMPLOYEE DETAILS

PROGRAM DEFINITION
To write a C++ program to display the details of the employee using Inheritance.

PROGRAM ANALYSIS
struct date
A structure date which contains the day(dd),month(mm), year(yy) which is declared globally.
This structure is used to obtain the date of birth(dob) and date of joining(doj) from the user.
class person
A class person which contains the private data members such as name, dob(date of
birth),educational qualification(eq).
void accept()
This is the public data member function which is used to obtain the details of the employee.
void output()
This function prints the name, dob and educational qualification of a person.
class emp::public person
This class emp contains data members-date of joining and salary. This class emp is a derived
class and it is inherited from the base class person. It is a publicly derived class. The base class
protected and public members are inherited as protected and public members itself in the public
visibility mode.
void accept2()
This function calls the base class member function accept() as well as it gets the values of its
own data members.
void output2()
This function calls the output() function and also displays the details of its own members.
class manager::public emp
This class manager is inherited from emp which illustrates the concept of multilevel
inheritance. This class contains number of subordinates and also the designation.
void in()
This function accepts the details of the base class members.
This function accepts no. of subordinates and designation from the user.
void out()
This function displays the details of the base class and its own class.
PROGRAM CODING
//Employee Details
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
struct date
{
int dd, mm, yy;
};
class person
{
protected:
char name[20];
date dob;
char eq[20];
public:
void accept()
{
cout<<"\nEnter the name: ";
gets(name);
cout<<"Enter the date of birth ";
cin>>dob.dd>>dob.mm>>dob.yy;
cout<<"Enter the educational qualification: ";
gets(eq);
}
void output()
{
cout<<"\nName: "<<name;
cout<<"\nDate of Birth: "<<dob.dd<<"/"<<dob.mm<<"/"<<dob.yy;
cout<<"\nEducational Qualification: "<<eq;
}
};
class emp:public person
{
protected:
date doj;
int ec;
float sal;
public:
void accept2()
{
accept();
cout<<"\nEnter the employee code: ";
cin>>ec;
cout<<"Enter the date of joining ";
cin>>doj.dd>>doj.mm>>doj.yy;
cout<<"Enter the salary: ";
cin>>sal;
}
void output2()
{
output();
cout<<"\nEmployee code: "<<ec;
cout<<"\nDate of Joining: "<<doj.dd<<"/"<<doj.mm<<"/"<<doj.yy;
cout<<"\nSalary: "<<sal;
}

};
class manager:public emp
{
int no;
char title[30];
public:
void in()
{
accept2();
cout<<"\nEnter the number of subordinates: ";
cin>>no;
cout<<"Enter the designation: ";
gets(title);
}
void out()
{
output2();
cout<<"\nNumber of subordinates: "<<no;
cout<<"\nDesignation: "<<title;
}
};
void main()
{
clrscr();
emp e;
manager m;
cout<<"\nEnter the employee details:\n";
e.accept2();
cout<<"\nEnter the manager details:\n";
m.in();
cout<<"\n\n\t\tEMPLOYEE DETAILS";
cout<<"\n\t\t****************\n";
e.output2();
cout<<"\n\n\t\tMANAGER DETAILS";
cout<<"\n\t\t***************\n";
m.out();
getch();
}
INPUT AND OUTPUT

Enter the employee details:

Enter the name: girish


Enter the date of birth 12 12 1992
Enter the educational qualification: BE

Enter the employee code: 123


Enter the date of joining 21 06 2015
Enter the salary: 25000

Enter the manager details:

Enter the name: hariharan


Enter the date of birth 12 01 1989
Enter the educational qualification: BE

Enter the employee code: 100


Enter the date of joining 17 04 2011
Enter the salary: 50000

Enter the number of subordinates: 1


Enter the designation: BE

EMPLOYEE DETAILS
****************

Name: girish
Date of Birth: 12/12/1992
Educational Qualification: BE
Employee code: 123
Date of Joining: 21/6/2015
Salary: 25000

MANAGER DETAILS
***************

Name: hariharan
Date of Birth: 12/1/1989
Educational Qualification: BE
Employee code: 100
Date of Joining: 17/4/2011
Salary: 50000
Number of subordinates: 1
Designation: BE

RESULT
Thus the C++ program to print the details of the employee using the multilevel inheritance is
executed successfully.

Program 7 Text file creation and manipulation

PROGRAM DEFINITION

To write a C++ program to create a text file and process the text file to perform operations with
it.

PROGRAM ANALYSIS

Create a text file using the ofstream fout;

fout.open(“ARTICLE.TXT” ,ios::out); - This file creates a new file ARTICLE.TXT .

The content of the file is written using fout<<”content of the file should be typed here”

The file is closed using fout.close();

The file is opened in the read mode for processing. Ifstream fin(“ARTICLE.TXT”,ios::in);

Read the content of the file and compare each word with “ this” or “these” using strcmp function

Display the no. of “this” or “these” present in the text.

The file should be closed using fin.close();

//Program for text file handling

#include<fstream.h>

#include<string.h>
#include<conio.h>

#include<iostream.h>

void main()

ofstream fout(“c:/tc/bin/article.txt”,ios::out);

fout<<”This is the passage which teaches us file handling. These files are used for maintaining
data.

These files when opened in output mode are used for writing. This file opened in input
mode is

used for reading.”

fout.close();

ifstream fin;

fin.open("C:/TC/BIN/ARTICLE.TXT",ios::in);

char word[50];

int c1=0,c2=0;

while(!fin.eof())

{ fin>>word;

if(strcmpi(word,"this")==0)

c1++;

if(strcmpi(word,"these")==0)

c2++; }

cout<<"count of \'this\'in file is:"<<c1;

cout<<"count of \'these\'in file is:"<<c2;

fin.close(); }
SAMPLE INPUT AND OUTPUT

This is the passage which teaches us file handling. These files are used for maintaining data.
These files when opened in output mode are used for writing. This file opened in input mode is
used for reading.
count of ‘this’ in file is: 2
count of ‘these’ in file is:2

Program 8 PAYROLL PROCESSING-BINARY FILE HANDLING

PROGRAM DEFINITION
To write a C++ program to create a binary file and calculate the salary of the employee by
reading the data from the binary file.

PROGRAM ANALYSIS

class employee

This class contains ec,name,gross,hra,basic,pf,da, net as private data members and the following
member functions.

employee()

A constructor function which is used to initialize the values of gross, net,basic and pf to be 0.
The hra is initialized to 500 and the da is initialized to 300.

voi d input()

This function is used to get all the values from the user. (code, name and basic)

void calc() – This function calculates the net salary as

da= .15*(basic+da);

pf = .1033*(basic+da);

gross= basic+da+hra;

net = gross-pf;

void output() – This function displays the code, name, basic, da, hra, gross pf and net salary of
the employee.

void main() – The object for class employee is created. The file is opened in fstream mode to
have input and output operations in the file. The content is written in to the file.
fstream f(“emp.dat”,ios::out|ios::binary);

To write data in to the binary file

f.write((char *)&e,sizeof(e));

To read data from the file

f.read((char*)&e,sizeof(e));

The details of the employees are received from the user and then written into the file. The
employee details are then read from a file and the salary of the employee is calculated using void
calc() and displayed using void output().

The file is closed f.close();

PROGRAM CODING

//Payroll Processing
#include<fstream.h>
#include<stdio.h>
#include<conio.h>
class employee
{
int ec;
char name[80];
float gross, hra, basic, pf, da, net;
public:
employee()
{
gross=net=basic=pf=0.0;
hra=600.0;
da=300.0;
}
void input()
{
cout<<"\nEnter the employee code: ";
cin>>ec;
cout<<"Enter the name of the employee: ";
gets(name);
cout<<"Enter the basic pay: ";
cin>>basic;
}
void calc()
{
da=0.15*(basic+da);
pf=0.1033*(basic+da);
gross=basic+da+hra;
net=gross-pf;
}
void output()
{
cout<<"\n\t\t\tPAY SLIP";
cout<<"\n\t\t\t--------------";
cout<<"\nEmployee code: "<<ec;
cout<<"\nName: "<<name;
cout<<"\nBasic Pay: "<<basic;
cout<<"\nDA: "<<da;
cout<<"\nHRA: "<<hra;
cout<<"\nGross: "<<gross;
cout<<"\nProvident Fund: "<<pf;
cout<<"\nNet: "<<net;
}
};
void main()
{
clrscr();
employee e;
fstream f("emp.dat",ios::out|ios::binary);
cout<<"\n\t\t\tPAYROLL PROCESSING";
cout<<"\n\t\t\t**********************";
int n, i=0;
cout<<"\nEnter the number of employees: ";
cin>>n;
do
{
cout<<"\nEnter the details of Employee "<<i+1<<":\n";
e.input();
f.write((char *)&e,sizeof(e));
i++;
}while(i<n);
f.close();
f.open("emp.dat",ios::in|ios::binary);
while(f.read((char *)&e,sizeof(e)))
{
e.calc();
e.output();
}
f.close();
getch();
}
INPUT AND OUTPUT

PAYROLL PROCESSING
**********************
Enter the number of employees: 1

Enter the details of Employee 1:

Enter the employee code: 1001


Enter the name of the employee: Ramesh
Enter the basic pay: 6000

PAY SLIP
--------------
Employee code: 1001
Name: Ramesh
Basic Pay: 6000
DA: 945
HRA: 600
Gross: 7545
Provident Fund: 717.418518
Net: 6827.581543

Program 9 Binary File Processing – Search

PROGRAM DEFINITION
To write a C++ program to perform binary file processing to search records.
PROGRAM ANALYSIS

class CLUB – This class contains mno-membership number, mname-membership name and
membership type as data members and reg() , display() and whattype() as member functions.
void reg() – To accept the details of the data members from the user.
void display() – To display the details of the data members()
char whattype() – returns the value of the private data member type

void main() – A file by named club.dat is created and records are written in to it by using
ofstream fout;
fout.open("club.dat",ios::binary|ios::out);
fout.write((char *)&c,sizeof(c));

Then the file is opened in the read mode and the type is checked. If the type is L or M then the
records are displayed using display() function.
ifstream fin;
fin.open("club.dat",ios::binary|ios::in);
fin.read((char *)&c,sizeof(c))

PROGRAM CODING

#include <fstream.h>
#include <conio.h>
#include<stdio.h>
class CLUB
{
int mno;
char mname[20];
char type;
public:
void reg()
{
cout<<"\nEnter Member no:";
cin>>mno;
cout<<"\nEnter Member name:";
gets(mname);
cout<<"Enter Membership type - L or M or Q or H";
cin>>type;
}
void display()
{
cout<<"\nDetails of the members:\n";
cout<<"Membership Number:"<<mno;
cout<<"Member Name:"<<mname;
cout<<"Membership Type:"<<type;
}
char whattype()
{
return type;
}
};
void main ()
{
clrscr();
CLUB c; char ch;
ofstream fout;
fout.open("club.dat",ios::binary|ios::out);
do
{
c.reg();
fout.write((char *)&c,sizeof(c));
cout<<"\nDo you want to continue:Enter y or n:";
cin>>ch;
}while(ch=='y');
fout.close();
ifstream fin;
fin.open("club.dat",ios::binary|ios::in);
while(fin.read((char *)&c,sizeof(c)))
{
if(c.whattype()=='L'||c.whattype()=='M')
c.display();
}
fin.close();
getch();
}

INPUT AND OUTPUT


Enter Member no:1

Enter Member name:aravind


Enter Membership type - L or M or Q or HL

Do you want to continue:Enter y or n:y

Enter Member no:2

Enter Member name:praveen


Enter Membership type - L or M or Q or HM

Do you want to continue:Enter y or n:y

Enter Member no:3

Enter Member name:sowmya


Enter Membership type - L or M or Q or HQ

Do you want to continue:Enter y or n:y

Enter Member no:4

Enter Member name:keerthana

Details of the members whose type is L or M:

Membership Number:1
Member Name:aravind
Membership Type:L

Details of the members whose type is L or M:

Membership Number:2
Member Name:praveen
Membership Type:M
PROGRAM 10 Binary File Processing – Search and copying it in another file

PROGRAM DEFINITION
To write a C++ program to perform searching operation in a binary file.

PROGRAM ANALYSIS
class CLUB – This class contains mno-membership number, mname-membership name and
membership type as data members and reg() , display() and whattype() as member functions.
void reg() – To accept the details of the data members from the user.
void display() – To display the details of the data members()
char whattype() – returns the value of the private data member type
void main() – A binary file club.dat is created by using ofstream class. The same file is opened in the
input mode for reading from it. Another file newmem.dat is created and those members whose
type is L or M is copied on to this file.
if(c.whattype()=='L'||c.whattype()=='M')
fout1.write((char*)&c,sizeof(c));
The file newmem.dat is read and the records are displayed.

PROGRAM CODING

#include <fstream.h>
#include <conio.h>
#include<stdio.h>
class CLUB
{
int mno;
char mname[20];
char type;
public:
void reg()
{
cout<<"\nEnter Member no:";
cin>>mno;
cout<<"\nEnter Member name:";
gets(mname);
cout<<"Enter Membership type - L or M or Q or H";
cin>>type;
}
void display()
{
cout<<"\n\t\tDetails of the members:\n";
cout<<"\nMembership Number:"<<mno;
cout<<"\nMember Name:"<<mname;
cout<<"\nMembership Type:"<<type;
}
char whattype()
{
return type;
}
};
void main ()
{
clrscr();
CLUB c; char ch;
ofstream fout;
fout.open("club.dat",ios::binary|ios::out);
cout<<"\n File creation";
do
{
c.reg();
fout.write((char *)&c,sizeof(c));
cout<<"\nDo you want to continue:Enter y or n:";
cin>>ch;
}while(ch=='y');
fout.close();
ifstream fin;
fin.open("club.dat",ios::binary|ios::in);
ofstream fout1("newmem.dat",ios::binary|ios::out);
while(fin.read((char *)&c,sizeof(c)))
{
if(c.whattype()=='L'||c.whattype()=='M')
fout1.write((char*)&c,sizeof(c));
}
fin.close();
fout1.close();
cout<<"\nMembers whose type is L or M Reading from new file\n";
cout<<"------------------------------------------------------";
ifstream fin1("newmem.dat",ios::binary);
while(fin1.read((char*)&c,sizeof(c)))
{
c.display();
}
fin1.close();
getch();
}

INPUT AND OUTPUT

File creation
Enter Member no:1

Enter Member name:jaya


Enter Membership type - L or M or Q or HL

Do you want to continue:Enter y or n:y

Enter Member no:2

Enter Member name:bharath


Enter Membership type - L or M or Q or HQ

Do you want to continue:Enter y or n:n

Members whose type is L or M Reading from new file


------------------------------------------------------
Details of the members:

Membership Number:1
Member Name:jaya
Membership Type:L
Program 11 Binary Search – Array

PROGRAM DEFINITION
To write a C++ program to perform binary search operation to locate an element in
the array.

PROGRAM ANALYSIS

void main()- This function accepts n the number of elements in an array and also accepts n elements
from the user. The elements should be given in the ascending order. The function Bsearch is
invoked to search the position of the value to be searched which is obtained from the user.

int Bsearch(int[],int,int) - The position of the middle element in the array is obtained by
mid= (beg+last)/2 (where beg=0, last = size-1)
if the element in the mid position is the element that is searched for then that position is
returned to the main() otherwise if the value is greater than the middle element then beg = mid+1
else if the value searched is less than the middle element then last = mid-1. If the element is not
found the function returns -1.

Program Code:

#include<iostream.h>
#include<conio.h>
int Bsearch(int[],int,int);
void main()
{
clrscr();
int AR[50],ITEM,N,index;
cout<<"Enter desired array size (max. 50)...";
cin>>N;
cout<<"\nEnter array elements\n";
for(int i=0;i<N;i++)
{
cin>>AR[i];
}
cout<<"\nEnter element to be searched for ...";
cin>>ITEM;
index=Bsearch(AR,N,ITEM);
if(index==-1)
cout<<"\nSorry!! Given element could not be found.\n";
else
cout<<"\nElement found at index: "<<index<<", Position: "<<index+1<<"\n";
getch();
}
int Bsearch(int AR[],int size,int item)
{
int beg,last,mid;
beg=0; last=size-1;
while(beg<=last)
{
mid=(beg+last)/2;
if(item==AR[mid]) return mid;
else if(item>AR[mid]) beg=mid+1;
else last=mid-1;
}
return -1;
}

INPUT AND OUTPUT

Enter desired array size (max. 50)...5

Enter array elements


45
90
110
134
567

Enter element to be searched for ...110

Element found at index: 2, Position: 3

RESULT
Thus the C++ program to perform Binary search is executed successfully.

PROGRAM 12 LINEAR SEARCH


PROGRAM DEFINITION
To write a C++ program to perform linear search operation to locate an element in an
array of n integers.

PROGRAM ANALYSIS

void main() – This function accepts n as the number of elements in an array and the entire
elements in an array. The function Lsearch is invoked with the integer array, size and the element
to be searched as parameters to the function.

int Lsearch(int[],int,int) –This function travels through the entire array to locate the element to
be searched. If the element is found it returns the position to the main function. If it does not it
returns -1.

PROGRAM CODING

#include<iostream.h>
#include<conio.h>
int lsearch(int[],int,int);
void main()
{
int ar[50],item,n,index;
cout<<"Enter desired array size(max 50)..";
cin>>n;
cout<<"Enter array elements\n";
for(int i=0;i<n;i++)
{
cin>>ar[i];
}
cout<<"Enter elements to be searched\n";
cin>>item;
index=lsearch(ar,n,item);
if(index==-1)
cout<<"sorry given element not found\n";
else
cout<<"Element found at index:"<<index<<",position:"<<index+1<<endl;
getch();
}
int lsearch(int ar[],int size,int item)
{
for(int i=0;i<size;i++)
{
if(ar[i]==item)
return i;
}
return -1;
}

INPUT AND OUTPUT

Enter desired array size(max 50)..7


Enter array elements
12
15
76
1
24
64
89
Enter elements to be searched
24
Element found at index:4,position:5

RESULT
Thus the C++ program to perform linear search among array of n integers is executed
successfully.

Program 13 Sorting and Searching – Array(Selection sort and Binary Search)

Program Definition

To write a c++ program to perform selection sort to sort the elements in an array and to
perform binary search to find the position of a particular element in the array.

Program Analysis
void main() - This function accepts the size of the array from the user and then accepts the array
elements from the user. The function sort is invoked by passing the array elements, the size as
the parameter to the function. Then the function search is invoked by passing the sorted array
elements, the size and then the item to be searched.

void sort (int a[], int n)

This function assigns the first element in the array as the smallest element and the position of the
element is also saved. It then examines the other elements in the array and changes the value of
the smallest element.(swapping). It is continued till all the elements in the array are sorted.

void search(int a[], int n, int item)

This function set the lower limit as 0 and the upper limit as size-1. The middle element is found
by adding lower limit and upper limit and dividing it by 2. The item to be searched is then
examined to be either in the upper half or lower half. If it is in the lower half then the upper limit
is set as the position of middle element -1 otherwise lower limit is set as the position of middle
element +1.

If(item==a[mid]) then the position is displayed.

PROGRAM CODING

//Sorting and Searching

#include<iostream.h>

#include<conio.h>

void sort (int a[], int n)

int small, pos, temp, i, j;

for (i=0; i<n; i++)

small=a[i];

pos=i;

for (j=i; j<n; j++)


{

if (a[j]<small)

{ small=a[j];

pos=j;

temp=a[i];

a[i]=a[pos];

a[pos]=temp;

cout<<"\nThe sorted array is:\n";

for (i=0;i<n;i++)

cout<<a[i]<<" ";

void search(int a[], int n, int item)

int l1=0, u1, mid, flag=0;

u1=n-1;

while(l1<=u1)

mid=(l1+u1)/2;

if(item==a[mid])

{ flag++;

cout<<"'"<<item<<"' is present in position: "<<mid+1;


}

if(item<a[mid])

u1=mid-1;

else

l1=mid+1;

if(flag==0)

cout<<"\nElement not found!";

void main()

clrscr();

int a[20], n, item, i;

char ch;

do

cout<<"\n\n\t\tSORTING AND SEARCHING";

cout<<"\n\t\t*********************";

cout<<"\n\nEnter the size of the array: ";

cin>>n;

cout<<"Enter the elements of the array: ";

for(i=0;i<n;i++)

cin>>a[i];

sort(a,n);
cout<<"\n\nEnter the element to be searched: ";

cin>>item;

search(a,n,item);

cout<<"\n\nDo you want to continue? (Y/N): ";

cin>>ch;

}while(ch=='y'||ch=='Y');

getch();

Sample Input and Output

SORTING AND SEARCHING

*********************

Enter the size of the array: 6

Enter the elements of the array: 23 45 12 2 -9 65

The sorted array is:

-9 2 12 23 45 65

Enter the element to be searched: 23

'23' is present in position: 4

Do you want to continue? (Y/N): y

SORTING AND SEARCHING

*********************

Enter the size of the array: 5

Enter the elements of the array: 112 56 789 16 0


The sorted array is:

0 16 56 112 789

Enter the element to be searched: 0

'0' is present in position: 1

Do you want to continue? (Y/N): n

Program 14 Bubble sort - Structure

Program Definition

To write a C++ program to perform bubble sort operation using a structure.

Program Analysis

A structure emp is created with eno, name and salary. Structure variables are created.

void main() – The number of employees n is inputted from the user. This function gets the
details of the employees(their number, name and salary). The function bubblesort is invoked
from this function. The result that is the details of the employees arranged in descending order of
salary are printed.

void bubblesort(empe[],int size)

This function performs the sorting using the following loop structure

for(i=0;i<size;i++)

for(j=0;j<size-1-i;j++)

{
if(e[j].sal<e[j+1].sal)

temp=e[j];

e[j]=e[j+1];

e[j+1]=temp;

}}}

The consecutive elements are compared and interchanged. So after each iteration the heaviest
element settles down at the bottom. So the comparison is done with the remaining elements. A
temporary variable is used to swap the elements.

Program Code:
#include<iostream.h>
#include<conio.h>
struct emp
{
int eno;
char name[25];
float sal;
}e[10];
void bubblesort(emp e[],int size)
{
int i,j;
emp temp;
for(i=0;i<size;i++)
{
for(j=0;j<size-1-i;j++)
{
if(e[j].sal<e[j+1].sal)
{
temp=e[j];
e[j]=e[j+1];
e[j+1]=temp;
}
}
}
}
void main()
{
clrscr();
int n;
int i;
cout<<"Enter no of employees:";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter"<<i+1<< " Employee no name and salary\n";
cin>>e[i].eno;
cin>>e[i].name;
cin>>e[i].sal;
}
bubblesort(e,n);
cout<<"\n The arranged structure in descending order\n";
for(i=0;i<n;i++)
{
cout<<"\nThe detail of"<<i+1<< " Employee no name and salary\n";
cout<<e[i].eno<<endl;
cout<<e[i].name<<endl;
cout<<e[i].sal<<endl;
}
getch();
}

INPUT AND OUTPUT

Enter no of employees:3
Enter1 Employee no name and salary
1101 arjun 25000
Enter2 Employee no name and salary
1102 akash 45000
Enter3 Employee no name and salary
1103 sunitha 32000

The arranged structure in descending order

The detail of1 Employee no name and salary


1102
akash
45000

The detail of2 Employee no name and salary


1103
sunitha
32000

The detail of3 Employee no name and salary


1101
arjun
25000

PROGRAM 15 MERGE SORT

Program Definition

To write a C++ program to perform merge sort operations in arrays.

Program Analysis

void main()- This function accepts two arrays from the user and invokes the function mergesort.
The array A is arranged in the ascending order and array B in descending order.

merge(a,b,c,m,n);- function invoke

void merge(int a[], int b[], int c[], int m, int n)

This function checks for the element in the array A with the element in array B. The smallest
element is copied to array c.

for(i=0,j=n-1,k=0;(i<m)&&(j>=0);k++)
{ if(a[i]<b[j])
{ c[k]=a[i];
i++;
}
else
{ c[k]=b[j];
j--;
}
}
while(i<m)
{ c[k]=a[i];
i++;
k++;
}
while(j>=0)
{ c[k]=b[j];
j--;
k++;
}
//Merge-Sort
#include<iostream.h>
#include<conio.h>
void merge(int a[], int b[], int c[], int m, int n)
{
int i, j, k;
for(i=0,j=n-1,k=0;(i<m)&&(j>=0);k++)
{ if(a[i]<b[j])
{ c[k]=a[i];
i++;
}
else
{ c[k]=b[j];
j--;
}
}
while(i<m)
{ c[k]=a[i];
i++;
k++;
}
while(j>=0)
{ c[k]=b[j];
j--;
k++;
}
cout<<"\nThe merged array is:\n";
for(k=0;k<m+n;k++)
cout<<c[k]<<" ";
}
void main()
{
clrscr();
int a[50], b[50], c[100], m, n;
cout<<"\n\t\tMERGING OF ARRAYS";
cout<<"\n\t\t*****************";
cout<<"\n\nEnter the size of array A: ";
cin>>m;
cout<<"Enter the elements of array A (must be in ascending order): ";
for(int i=0;i<m;i++)
cin>>a[i];
cout<<"\nEnter the size of array B: ";
cin>>n;
cout<<"Enter the elements of array B (must be in descending order): ";
for(int j=0;j<n;j++)
cin>>b[j];
merge(a,b,c,m,n);
getch();
}

INPUT AND OUTPUT

MERGING OF ARRAYS
********************

Enter the size of array A: 3


Enter the elements of array A (must be in ascending order): 2
5
6

Enter the size of array B: 4


Enter the elements of array B (must be in descending order): 64
4
1
-5

The merged array is:


-5 1 2 4 5 6 64

Program 16 Linked Stack

Program Definition

To write a C++ program to perform push and pop operations in a linked stack.

Program Analysis

void main() – This function accepts choice from the user to perform whether to perform push and
pop operations in a linked stack.

A self referential structure is created to form linked list.

struct node
{

char name[20];

int age;

node *link; - A pointer to the same type of node.

};

class stack- This class contains *top and *ptr as data members which points to the top most
element in the stack and ptr points to a node.

stack() – This is the constructor in which the topmost node points to NULL.

void stackpush() - A new node is created by using new operator. The information is obtained
from the user. The top pointer is checked if it is NULL then a new node is made as the topmost
element in the stack. If the stack contains elements then the already existing top node is removed
and the new node is made as the top node and the link of the topmost node is given to the
previous topmost node.

void stackpop(){

if(top==NULL)
cout<<"\nUnderflow!";
else
{ ptr=top;
top=top->link;
delete ptr;
}
cout<<"\nNow the stack is:\n";
display(top);
}
The topmost node is to be deleted and the memory is to be released. The topmost node is copied
on to the temporary pointer and the top most node link is pointed to the next node.
The display function is invoked to display the elements in the stack.

PROGRAM CODING
//Linked Stack program
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
struct node
{
char name[20];
int age;
node *link;
};
class stack
{
node *top, *ptr;
public:
stack() { top=NULL; }
void stackpush()
{
node *newptr;
newptr=new node;
newptr->link=NULL;
cout<<"\nEnter the name: ";
gets(newptr->name);
cout<<"Enter the age: ";
cin>>newptr->age;
if(top==NULL)
top=newptr;
else
{ ptr=top;
top=newptr;
newptr->link=ptr;
}
cout<<"\nNow the stack is:\n";
display(top);
}
void stackpop()
{
if(top==NULL)
cout<<"\nUnderflow!";
else
{ ptr=top;
top=top->link;
delete ptr;
}
cout<<"\nNow the stack is:\n";
display(top);
}
void display(node *np);
}obj;
void stack::display(node *np)
{
while(np!=NULL)
{ cout<<np->name<<" "<<np->age<<"->";
np=np->link;
}
}
void main()
{
clrscr();
char ch;
int c;
do
{
cout<<"\n\t\t\tINSERTION AND DELETION IN A STACK";
cout<<"\n\t\t\t*********************************";
cout<<"\n1.Insertion\n2.Deletion";
cout<<"\nEnter your choice: ";
cin>>c;
switch(c)
{
case 1: cout<<"\nInsert the element:";
obj.stackpush();
break;
case 2: obj.stackpop();
break;
}
cout<<"\nDo you want to continue?(Y/N): ";
cin>>ch;
}while(ch=='y'||ch=='Y');
getch();
}

Output
INSERTION AND DELETION IN A STACK
*********************************
1.Insertion
2.Deletion
Enter your choice: 1

Insert the element:


Enter the name: seshadri
Enter the age: 17

Now the stack is:


seshadri 17->
Do you want to continue?(Y/N): y

INSERTION AND DELETION IN A STACK


*********************************
1.Insertion
2.Deletion
Enter your choice: 1

Insert the element:


Enter the name: ses
Enter the age: 16

Now the stack is:


ses 16->seshadri 17->
Do you want to continue?(Y/N): y

INSERTION AND DELETION IN A STACK


*********************************
1.Insertion
2.Deletion
Enter your choice: 2

Now the stack is:


seshadri 17->
Do you want to continue?(Y/N):N

PROGRAM 17 REVERSING A STRING(STACK as array)

PROGRAM DEFINITION
To write a C++ program to reverse a string using STACK as a array.

PROGRAM ANALYSIS
class stack – This contains char a[]- to hold a string, int top.
stack()- This constructor initializes the value of the top to be -1.

void push(char * item); - This function inserts the characters in to the stack by incrementing the
top by 1 and then inserting the element a[top]=item.

void pop(char & item); - It retrieves the element from the stack array by decrementing the top
pointer by 1..
void reverse(char str[],int len); - This function declares a char newstr[] array and invokes the
function push and then pop to reverse the given string.
void main() – This function gets the string from the user and passes it to the function reverse.

//Reverse a string
#include<iostream.h>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<conio.h>
const int max=50;
class stack
{
char a[max];
int top;
public:
stack() { top=-1;}
void push(char item)
{
if(top<max-1)
{ top++;
a[top]=item;
}
else
{ cout<<"\nError!";
return;
}
}
void pop(char &item)
{
if(top>-1)
{ item=a[top];
top--;
}
else
{ cout<<"\nError!";
return;
}
}
};
void reverse(char str[], int len)
{
stack string;
char newstr[50];
int i;
for(i=0;i<len;i++)
string.push(str[i]);
for(i=0;i<len;i++)
string.pop(newstr[i]);
newstr[len]='\0';
cout<<"\nThe reversed string is: ";
puts(newstr);
}
void main()
{
clrscr();
char str[50];
int len;
cout<<"\n\t\t\tREVERSE A STRING";
cout<<"\n\t\t\t~~~~~~~~~~~~~~~~";
cout<<"\nEnter the string to be reversed: ";
gets(str);
len=strlen(str);
reverse(str,len);
getch();
}

OUTPUT
REVERSE A STRING
~~~~~~~~~~~~~~~~
Enter the string to be reversed: amrutha

The reversed string is: ahturma

PROGRAM 18 Hexadecimal Conversion(Linked stack)

PROGRAM DEFINITION
To write a C++ program to convert a decimal number to its hexadecimal conversion using stack
as a Linked list.
PROGRAM ANALYSIS

struct node – This contains char info, *link – pointer of same data type.

class stack – this contains *top – pointer to a structure.


stack() – This function initializes the top value to NULL.
int push(char c); - This function creates a new node and then inserts a character on the top
position.(in the front).
int pop(char & item) – This function retrieves the element on the top position and then the top
pointer is made to point to the previous node. This gives us the hexadecimal equivalent of the
given decimal number.
void main() – This function declares m and n as long data type and char m. s is an object to class
stack. The decimal number is obtained from the user. The function push is called till the quotient
is not equal to zero when divided by 16. The remainders are inserted in to the stack. The function
pop invoked in the reverse order to print the hexadecimal equivalent.

SOURCE CODE
//Hexadecimal conversion
#include<iostream.h>
#include<alloc.h>
#include<process.h>
#include<conio.h>
struct node
{
char info;
node *link;
};
class stack
{
node *top;
public:
stack() { top=NULL; }
int push(char c)
{
node *p=new node;
if(!p)
return 0;
p->info=c;
p->link=top;
top=p;
return 1;
}
int pop(char &item)
{
if(top==NULL)
return 0;
node *p=top;
item=p->info;
top=p->link;
delete p;
return 1;
}
};
void main()
{
clrscr();
long m, n;
char r;
stack s;
char h[]="0123456789ABCDEF";
cout<<"\n\t\t\tDECIMAL TO HEXADECIMAL CONVERSION";
cout<<"\n\t\t\t*********************************";
cout<<"\nEnter the decimal number: ";
cin>>n;
m=n;
for(;m!=0;m/=16)
if(s.push(h[m%16])==0)
{ cout<<"\nStack is full!";
getch();
exit(0);
}
cout<<"\nThe hexadecimal equivalent of "<<n<<" is: ";
for(;s.pop(r)!=0;)
cout<<r;
getch();
}
DECIMAL TO HEXADECIMAL CONVERSION
*********************************
Enter the decimal number: 123

The hexadecimal equivalent of 123 is: 7B

PROGRAM 19 LINKED QUEUE

PROGRAM DEFINITION
To write a C++ program to perform insert, delete operations in a dynamically
allocated queue.

PROGRAM ANALYSIS
struct node – A self referential structure which contains city and a link (a pointer) variable.
class queue – It contains rear , front which are the pointer to structures.
The member functions include ins(), del() and display()
A constructor queue() to initialize NULL pointer to rear and front.
The function ins() creates a new node and allocates it to the rear end of the queue and the
new node inserted becomes the rear node.
The function del() transfers the node in the front to a temporary pointer and deletes it to
deallocate the memory. The front pointer is made to point to the next node.
The display() function displays all the node from the beginning till it reaches the end which is
NULL.

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
struct node
{
char city[20];
node *link;
};
class queue
{
node *rear,*front;
public:
queue()
{
rear=NULL;
front=NULL;
}
void ins();
void del();
void display();
~queue();
};
void queue::ins()
{
node *temp=new node;
cout<<”Enter city name”;
gets(temp->city);
temp->link=NULL;
if(rear==NULL)
{
rear=front=temp;
}

else
{
rear->link=temp;
rear=temp;
}
}
void queue::del()
{
if(front==NULL)
cout<<"UNDERFLOW";
else
{
node *ptr=front;
cout<<front->city<<"Deleted/n";
front=front->link;
delete ptr;
{if(front==NULL)
rear=NULL;
}
}
}
void queue::display()
{
node *temp=front;
while(temp!=NULL)
{
cout<<temp->city<<"->";
temp=temp->link;
}
cout<<"!!!\n";

}
queue::~queue()
{ node *temp;
while(front!=NULL)
{
temp=front;
front=front->link;
delete temp;
}
}
void main()
{
clrscr();
queue qt;
int ch;
while(1)
{
cout<<"Menu:\n1)Insert \n2)Delete \n3)Display \n 4)Exit\n";
cout<<"Enter ur choice";
cin>>ch;
switch(ch)
{
case 1: qt.ins();
break;
case 2: qt.del();
break;
case 3: qt.display();
break;
case 4: exit(0);
default: cout<<"Wrong choice made";
}
}
}

OUTPUT
Menu:
1)Insert
2)Delete
3)Display
4)Exit
Enter ur choice1
Enter city name
chennai
Menu:
1)Insert
2)Delete
3)Display
4)Exit
Enter ur choice1
Enter city name
coimbatore
Menu:
1)Insert
2)Delete
3)Display
4)Exit
Enter ur choice3
chennai->coimbatore->!!!
Menu:
1)Insert
2)Delete
3)Display
4)Exit
Enter ur choice2
chennaiDeleted/nMenu:
1)Insert
2)Delete
3)Display
4)Exit
Enter ur choice3
coimbatore->!!!
Menu:
1)Insert
2)Delete
3)Display
4)Exit
Enter ur choice4

PROGRAM 20 CIRCULAR QUEUE (as an array)

PROGRAM DEFINITION
To write a C++ program to perform insertion and deletion from a circular queue(as an array).
PROGRAM ANALYSIS

class cqu - This class contains the data members int cq[5], int f, int r which denotes the array of
5 elements, the front position and the rear elements in the circular queue.
cqu() - The constructor which initializes the values of f and r to -1.
void ins(int item) – To insert element in the rear position of the queue.
void ins(int item)
{ if((f==0&&r==4)||(f==r+1))// front = rear+1 because of circular queue
{ cout<<"\nCircular Queue is full"; // checks the overflow condition
return;
}
else if(r==-1) // beginning the queue when the queue does not exist
f=r=0;
else if(r==4) // rear has reached the size then rear becomes 0 (circular
queue)
r=0;
else
r=r+1; // rear is incremented normal insertion
cq[r]=item; // the element is inserted in the cq array at rear position
}

void del(int &item) // deletes the element from the front


{ item=cq[f];
if(f==r)
f=r=-1; // front and rear are same only one element in the queue
(reset)
else if(f==4)
f=0;//size has reached then front is 0
else
f=f+1; // increments the front position(normal deletion in the
queue)
}

void display()- This function displays all the elements


void display()
{ if(f==-1)
{ cout<<"\nCircular Queue is empty";
return;
}
if(f<=r)
{ cout<<"\n";
for(i=f;i<=r;i++)
cout<<cq[i]<<" ";
}
if(r<f)
{ cout<<"\n";
for(i=f;i<=4;i++)
cout<<cq[i]<<" ";
for(i=0;i<r;i++)
cout<<cq[i]<<" ";
}
}

SOURCE CODE
//Circular Queue
#include<iostream.h>
#include<process.h>
#include<conio.h>
int i;
class cqu
{ int cq[5], f, r;
public:
cqu()
{ f=r=-1;}
void ins(int item)
{ if((f==0&&r==4)||(f==r+1))
{ cout<<"\nCircular Queue is full";
return;
}
else if(r==-1)
f=r=0;
else if(r==4)
r=0;
else
r=r+1;
cq[r]=item;
}
void del(int &item)
{ item=cq[f];
if(f==r)
f=r=-1;
else if(f==4)
f=0;
else
f=f+1;
}
void display()
{ if(f==-1)
{ cout<<"\nCircular Queue is empty";
return;
}
if(f<=r)
{ cout<<"\n";
for(i=f;i<=r;i++)
cout<<cq[i]<<" ";
}
if(r<f)
{ cout<<"\n";
for(i=f;i<=4;i++)
cout<<cq[i]<<" ";
for(i=0;i<r;i++)
cout<<cq[i]<<" ";
}
}
};
void main()
{
clrscr();
int ch, item;
cqu cq;
cout<<"\n\t\t\tCIRCULAR QUEUE";
cout<<"\n\t\t\t**************";
do
{ cout<<"\n\nMenu";
cout<<"\n\n--------";
cout<<"\n1. Insertion\n2. Deletion\n3. Exit";
cout<<"\nEnter your choice: ";
cin>>ch;
switch(ch)
{ case 1: cout<<"\nEnter item to be inserted: ";
cin>>item;
cq.ins(item);
cq.display();
break;
case 2: cq.del(item);
cout<<"\nItem deleted";
cq.display();
break;
case 3: exit(0);
}
}while(1);
getch();
}
CIRCULAR QUEUE
**************

Menu

--------
1. Insertion
2. Deletion
3. Exit
Enter your choice: 1

Enter item to be inserted: 34

34

Menu

--------
1. Insertion
2. Deletion
3. Exit
Enter your choice: 1

Enter item to be inserted: 78

34 78

Menu

--------
1. Insertion
2. Deletion
3. Exit
Enter your choice: 1

Enter item to be inserted: 90

34 78 90

Menu

--------
1. Insertion
2. Deletion
3. Exit
Enter your choice: 1

Enter item to be inserted: 100


34 78 90 100

Menu

--------
1. Insertion
2. Deletion
3. Exit
Enter your choice: 1

Enter item to be inserted: 150

34 78 90 100 150

Menu

--------
1. Insertion
2. Deletion
3. Exit
Enter your choice: 1

Enter item to be inserted: 200

Circular Queue is full


34 78 90 100 150

Menu

--------
1. Insertion
2. Deletion
3. Exit
Enter your choice: 2

Item deleted
78 90 100 150

Menu
--------
1. Insertion
2. Deletion
3. Exit
Enter your choice: 2

Item deleted
90 100 150

Menu
--------
1. Insertion
2. Deletion
3. Exit
Enter your choice: 3

PROGRAM 21 DISTANCE CALCULATION – PASSING OBJECTS

PROGRAM DEFINITION

To write a C++ program to add two distances to illustrate how objects are passed to
functions and how objects are returned by functions.

PROGRAM ANALYSIS

class Distance - This class contains two private integer data members feet and inches.
The public data member functions are:
void getdata(int f, int i);

This function assigns the value to the data members.


void printit(void);
This function prints the values of feet and inches.

Distance sum(Distance d2);


This function adds two distance. The sum function accepts distance as parameters and adds
with the current instance through which the function is called.

Distance d3;
d3.feet = feet+d2.feet +(inches+d2.inches)/12;
d3.inches=(inches+d2.inches)%12;
return d3;

void main() – Three objects length1, length2, total are created for class Distance. The getdata()
function passes two values feet and inches as parameters. The sum functions is called by
total = length1.sum(length2);
The function sum returns the object of type Distance.(total)

OUTPUT:
Length 1: 23Feet 9Inches
Length 2: 12Feet 9Inches
Total Length: 36Feet 6Inches
PROGRAM CODING
#include<iostream.h>
#include<conio.h>
#include<iostream.h>
#include<conio.h>
class distance
{
private:
int feet, inches;
public:
void getdata(int f, int i)
{
feet=f;
inches=i;
}
void printit(void)
{
cout<<feet<<"Feet:"<<inches<<"Inches:"<<"\n";
}
distance sum(distance d2);
};
distance distance::sum(distance d2)
{
distance d3;
d3.feet=feet+d2.feet+(inches+d2.inches)/12;
d3.inches=(inches+d2.inches)%12;
return(d3);
}
void main()
{
distance length1, length2, total;
length1.getdata(23,9);
length2.getdata(12,9);
total=length1.sum(length2);
cout<<"Length 1:";
length1.printit();
cout<<"Length 2:";
length2.printit();
cout<<"Total Length:";
total.printit();
getch();
}
OUTPUT:
Length 1: 23Feet 9Inches
Length 2: 12Feet 9Inches
Total Length: 36Feet 6Inches
RESULT
Thus the program to add two distances by passing object as parameters and to return the object
to a function is executed.

PROGRAM 22 REVERSING THE ELEMENTS IN AN ARRAY

PROGRAM DEFINITION
To write a C++ program to reverse the elements in an array.

PROGRAM ANALYSIS
void swap( int a[],int n) – This function finds the position of the middle element in an
array. If the size is even then position = size/2 else the position =size/2 +1. Then the limit is fixed
to 0 to mid which is size/2. The elements are swapped.

void main() – The main() function gets the size and the elements as input from the user.
The function call swap(arrayname,size) is made.

PROGRAM CODING

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

void swap(int a[],int n)


{
int i,j,tmp,mid=n/2;
if(n%2==0)
j=mid;
else
j= mid+1;
for(i=0;i<mid;i++,j++)
{
tmp=a[i];
a[i]=a[j];
a[j]=tmp;
}
}

void main()
{
clrscr();
int a[10];int n,i;
cout<<"Enter the size of the array:";
cin>>n;
cout<<"\nEnter the elements:";
for(i=0;i<n;i++)
{
cin>>a[i];
}
swap(a,n);
cout<<"\nArray after swap:";
for(i=0;i<n;i++)
cout<<a[i]<<" ";
getch();
}

INPUT AND OUTPUT

Enter the size of the array:8

Enter the elements:1 2 3 4 5 6 7 8

Array after swap:5 6 7 8 1 2 3 4


PROGRAM 23 TWO DIMENSIONAL ARRAY FORMATION

PROGRAM DEFINITION

To write a C++ program to form a two dimensional array from a linear array.

PROGRAM ANALYSIS
This program declares a single and a two dimensional array. The value of n which is the
size of the array and the array elements are also obtained from the user. The position of the
elements where 0s to be filled is obtained by i+j >=n . The remaining elements are also copied.
The entire array is displayed.

PROGRAM CODING

#include <iostream.h>
#include <conio.h>
void main ()
{
clrscr ();
int a[10],n;
int b[10][10];
int i,j;
cout<<"Enter number of elements:";
cin>>n;
cout<<"\nEnter the elements of an array:";
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if((i+j)>=n)
b[i][j]=0;
else
b[i][j]=a[j];
}
}
cout<<"\nThe 2D array for the given linear array\n\n";
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout<<b[i][j]<<" ";
}
cout<<"\n\n";
}
getch();
}

INPUT AND OUTPUT

Enter number of elements:6

Enter the elements of an array:1 2 3 4 5 6

The 2D array for the given linear array

123456

123450

123400

123000

120000

100000
PROGRAM 24 MIDDLE ROW AND MIDDLE COLUMN ELEMENT IN AN ARRAY

PROGRAM DEFINITION
To write a C++ program to print the middle row and middle column element in array.

PROGRAM ANALYSIS

void middle(int a[3]3[3],int m, int n) - This function prints the middle row and column by
finding the middle position.

void main()- This function accepts the array and the function call is made.

PROGRAM CODING

#include <iostream.h>
#include <conio.h>
void middle(int a[3][3],int m, int n)
{
int i,j;
cout<<"middle row :";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i==(m/2))
cout<<a[i][j]<<" ";
}
}
cout<<"\n\nmiddle column:";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(j==(n/2))
cout<<a[i][j]<<" ";
}

}
void main()
{
clrscr ();
int i,j;
int a[3][3]={3,5,4,7,6,9,2,1,8};
cout<<"\nThe given matrix:\n";
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
middle(a,3,3);
getch();
}

INPUT AND OUTPUT

The given matrix:


354
769
218
middle row :7 6 9
middle column:5 6 1

PROGRAM 25 ROTATION FACTOR

PROGRAM DEFINITION

To write a C++ program to rotate the array elements with a rotation factor.

PROGRAM ANALYSIS

This program initializes the array elements and gets the rotation factor value from
the user. Another array is declared and the loop to change the values are

for(i=6;i>=0;i--)
{
if((i+r)>=7)
b[i+r-7]=a[i];
else
b[i+r]=a[i];
}
The resultant array is printed.

PROGRAM CODING

#include <iostream.h>
#include <conio.h>
void main ()
{
clrscr ();
int a[7]={22,31,12,44,5,17,1};
int r;
cout<<"\nEnter the rotation factor:";
cin>>r;
cout<<"\nThe original array is:\n"<<endl;
for(int i=0;i<7;i++)
cout<<a[i]<<" ";
int b[7];
for(i=6;i>=0;i--)
{
if((i+r)>=7)
b[i+r-7]=a[i];
else
b[i+r]=a[i];
}
cout<<"\n\nArray after rotation by factor "<<r<< " is\n"<<endl;
for(i=0;i<7;i++)
{
a[i]=b[i];
cout<<a[i]<<" ";
}
getch();
}

INPUT AND OUTPUT

Enter the rotation factor:3

The original array is:

22 31 12 44 5 17 1

Array after rotation by factor 3 is

5 17 1 22 31 12 44

You might also like