PART (1) Chapter
PART (1) Chapter
Chapter (7)
2. Create a program that test whether a given integer is zero or positive or negative.
# include <iostream.h>
void main ( )
int num;
cout << “Enter a number”;
cin >> num;
if (num <0) cout <<”Negative”;
else if (num >0) cout << “Positive”;
else cout << “Zero”;
}
3. Write a program that test on exam mark is pass, pass with Distinction or fail.
4. Write a program that will input numbers and find the maximum number and minimum numbers.
# include <iostream.h>
void main ( )
int x, y;
cout << “Enter two number”;
cin << x >> y;
if ( x > y )
cout << x << “is max” << y << “is min”;
else cout << y << “is max” << x << “is min”;
2
5. Write a program to sort the three integers a, b and c in ascending order. The number will be given from
the keyboard.
# include <iostream.h>
void main ( )
int a, b, c, max, mid, min;
cout << “Enter three numbers”;
cin >> a >> b >> c;
if (a > b && a > c)
max = a;
if (b>c)
mid = b;
min = c;
else mid = c
min = b
else mid = c;
min = a;
else max = c;
if (a > b)
mid =a;
min = b;
else mid = b;
min = a;
cout << min << “\t” << mid << “\t” << max;
6. Write a program to input two numbers and then display the following menu:
Sum of two numbers
Subtract the second number from the first
Multiply the two numbers by the second
Divide the two numbers by the second
None of the above
3
The program will then produce the output selected by the user from the menu.
#include <iostream.h>
void main
int a, b, x;
cout << “Enter two numbers”;
cin << a >> b;
cout << “ 1. Sum of two numbers”;
2. Subtract the second number from the first \n
3. Multiply the two numbers by the second \n
4. Divided the two numbers by the second \n
5. None of the above”
cout << “Enter select number”;
cin >> x ;
Switch (x)
case 1: cout << “Sum =” << a + b; break;
case 2: cout << “Subtract =” << a – b; break;
case 3: cout << “Multiply =” << a * b; break;
case 4: cout << “Divide =” << a/b ; break;
default: cout << “cout << “None of above”;
7. Write an appropriate control structure that will examine the value of a following point variable called
temp and print one of the following messages, depending on the value assigned to temp.
(a) ICE, if the value of temp is less than 0.
(b) WATER, if the value of temp lies between 0 and 100,
(c) STEAM, if the value of temp exceeds 100.
# include <iostream.h>
voice main ( )
float temp;
cout << “Enter temperature”;
cin >> temp;
if (temp < 0)
cout << “ICE”;
else if (temp >= 0 && temp <= 100)
cout << “WATER”;
else cout <<”STREAM”;
4
8. Write a program that reads a grade A, B, C, D or F and then print “Excellent”, “Good”, “Fair”, “Poor”,
and “Fail”.
# include <iostream.h>
void main ( )
char ch ;
cout << “Enter A, B, C, D or F”;
cin >> ch;
switch ( toupper (ch) )
case ‘A’ : cout << “Excellent”; break;
case ‘B’ : cout << “Good”; break;
case ‘C’ : cout << “Fair”; break;
case ‘D’ : cout “Poor”; break;
case ‘F’ : cout << “Fail”; break;
default : cout << “Invalid character”;
5
Chapter (8)
1. Write a program to calculate the sum of the given ten integers and then display the result. Ask the user to
input ten integers.
# include <iostream.h>
# include <iostream.h>
void man ( )
int i, num, sum = 0 ;
for ( i = 0; i < 10 ; i++ )
cout << “Enter a number”;
cin >> num;
sum += num;
cout << “\n The sum is” << sum;
2. Write a program to calculate the sum and average value of the given integers. (by while loop)
# include <stdio.h>
# include <conio.h>
void main ( )
int i = 0, sum = 0, num;
float avg;
cout << “Enter the number”;
cin >> num;
while (num = 0)
i++
sum += num;
cout << “Enter number”;
cin >> num;
avg = sum / i ;
cout << “The sum is” << sum;
cout << “The average is” << avg;
3. Write a program to calculate the sum and average value of the given integers. (by do while loop)
# include <iostream.h>
# include <conio.h>
# include <iomanip.h>
void main ( )
int i = 0, sum = 0, num;
float avg;
do
cout << “Enter the number”;
cin >> num;
i++ ;
while (I < 5)
avg = sum / 5 ;
cout << “The sum is” << sum;
cout << “The average is” << avg;
6
4. Write a program to find and display the sum of the successive even integers 2, 4, … 200.
# include <iostream.h>
# include <conio.h>
void main ( )
int i, sum = 0;
clrscr ( );
for ( i = 2; i <= 200; i+ = 2)
sum = sum + i ;
cout << “sum =” << ;
getch ( );
5. Write a program to find and display the sum of the successive add integers 1, 3, ….. 199.
# include <iostream.h>
# include <conio.h>
void main ( )
int i, sum = 0;
clrscr ( );
for ( i = 1; i <= 199; i += 2 )
sum = sum =+ i;
cout << “Sum =” << sum;
getch ( );
8. Suppose you deposit $ 50 per month in blank account every month for a year. Every month, after the
deposit has been made interest at the rate of 1 % is added to the balance. Eg. After one month, the balance is
$ 50.5, and after two month it is $ 101.51. Write a program to calculate the balance for one year.
# include <iostream.h>
void main ( )
int i ; float balance = 0 ; interest ;
cout << “month \t balance \n”;
for ( i = 1; i<= 12; i++ )
balance += 50;
interest = (balance * 1) / 100;
balance += interest;
cout << 1 << “\t” << balance << “\n”;
9. Ten students in a class write a test. Three subject marks enter as input data for each student. Write a
program which will read all ten students marks from the keyboard and determine the result as follow.
Roll No. Subject 1 Subject 2 Subject 3 Total Remark
1 67 85 70 222 Pass with Credit
2 35 68 59 162 Fail
3 70 60 57 187 Pass
. . . . . .
. . . . . .
. . . . . .
10 67 75 65 207 Pass
# include <iostream.h>
void main ( )
int i; m1, m2, m3;
cout << “Roll no \t sub 1 \t sub 2 \t sub 3 \t total \t remark \n”;
for ( i = 1; i <=10; i ++ )
cout << “Enter Students Marks”;
cin >> m1 >> m2 >>m3;
cout << i << “\t” << m1 << “\t” << m2 << “\t” << m3 << ‘\t” <<
(m1+m2+m3) << “\t”;
if ( m1 > 65 && m2 > 65 && m3 > 65 )
cout << “Pass with credit \n”;
else if ( m1 >= 50 && m2 >= 50 && m3 >= 50 )
cout << “Pass \n”;
else cout << “Fail \n”;
8
Chapter (9)
1. Create a function to calculate the sum and product of the given two integers. Write a program to
implement function.
# include <iostream.h>
int sum (int x, int y);
int mul (intx, int y);
void main ( )
int a, b;
cout << “Enter Two Number”;
cin >> a >> b;
cout << “Sum =” << (a, b);
cout << “Mul + “ << (a, b);
2. Write a function to calculate the area of a room. Ask the user to enter the length and width of the room.
# include <iostream.h>
int area (int x, int y);
void main ( )
int l, h, A;
cout << “Enter length and wide”;
cin >> l >> h;
A = area (l, b);
cout << “Area =” << A;
3. Write a function to calculate tax amount from the amount of purchase. Ask the user to enter the amount of
purchase and then call tax (float) function to calculate tax and then display the amount of purchase, amount
of tax and total amount. Use tax rate = 0.065.
9
# include <iostream.h>
float tax (float P);
void main ( )
float P;
cout << “Enter purchase”;
cin >> P;
float t = tax (p);
cout << “Purchase =” << P;
cout << “Tax =” << t;
cout << “Total =” << (p + t);
float tax (float P)
return (0.065 * P);
double a, x, y;
cout << “Enter a, x, y”;
cin >> a >> x >> y;
cout << “Xnew” << Xnew (x, y, a) << endl;
cout << “Ynew” << Ynew (x, y, a);
getch ( );
double Xnew (double x, double y, double a)
return (x * cos (a) + y * sin (a) );
double Ynew (double x, double y, double a)
return (-x * sin (a) + y * cos (a) );
# include <iostream.h>
# include <iostream.h>
double Mypow (double a, double b);
void main ( )
double a, b;
cout << “Enter a & b”;
cin >> a >> b;
cout << “Mypow =” << Mypow (a, b);
double Mypow (double a, double b)
return exp ( b * log (a) );
6. Write your own C++ function to compute the exponential function directly from the Tayler series:
ex + 1 + x + n2 / 2 + n3 / 3 + ---
# include <iostream.h>
double Myexp (double n);
void main ( )
double x;
cout <<”Enter x”;
cin >> x;
cout << “Myexp =” << Myexp (x);
double Myexp (double x)
double e = 1, d = 1, p = 1, f = 1, i = 1;
while ( d > 0.00001)
p *= x;
f *= I;
i++ ;
d = p/f;
e += d;
return exp;
7. Write a function Bin (int n, int r) which returns the binomial coefficient n(r(r-n)
# include <iostream.h>
double Bin (int n, int r);
int facto (int x);
void main ( )
int n, r;
cout << “Enter n & r”;
cin >> n >> r;
cout << Bin
double Bin (int n, int r)
double res;
res = (double) facto (n) / (facto (n) * facto (n – r) );
11
return res;
int facto (int x)
int f = 1;
for (i = 1;i <= x ; i++ )
f *= I;
return f;
8. Write a function to find the Fibonacci numbers are generated by the sequence 1, 1, 2, 3, 5, 8, 13, ….
# include <iostream.h>
void fibo (int n);
void main ( )
int n;
cout << “Enter How many numbers”;
cin >> n;
fibo (n);
void fibe (int n)
int f = 1, s = 1, t, n, I;
cout << f << “\t” << s << “\T” ;
for ( I = 3; I <= n; i++
t = f + s;
cout << t << “\t”;
f = s;
s = t;
void accept ( )
cout << “Enter three numbers”;
cin >> a >> b >> c;
m = x;
if (m > y) m = y;
if (m > z) m = z;
return m;
Chapter (10)
{
int i , num , max;
printf ( “Please enter 10 integers \n’’);
max= MAXANT;
for ( i=0; i<10; i+1)
{
Scanf (“ % d” , & num);
maximum (num, &max);
}
Printf (“ \n The maximum number entered was %d\n, max);
getch ( );
}
Void maximum ( int n, int* cmax )
{
if ( n> * cmax ) * cmax = n;
}
2. Write some statements to put some Fibonacci numbers (1, 2, 3, 5, 8, 13, …) int an array F[0],…. What is
the largest one which can be represented exactly?
# include < iostream .h >
void main ( )
{
int f [100] = {1,1};
int I;
cout << “ How many Fibonacci number’’ ;
cin >> n;
for ( i=0 ; i<n-2; i++ )
{ f[i+2] = f[i]+ f[i+1];
}
Cout << “the largest num” << f(n-1) ;
}
3. Salary level at any educational institution are (in thousand of dollars) 9, 10, 12, 15, 20, 35 and 50. The
numbers of employees at each level are respectively, 3000, 2500, 1500, 1000, 400, 100, 25. Write a program
which finds and writes.
(a) the average salary level;
(b) the number of employees above and below the average level,
(c) the average salary earned by an individual in the institution.
14
# include <iostream.h>
void main ( )
{ int I, total salary = 0, below + 0, above = 0, total = 0, total emp = o;
float avg salary , avg;
int s [7] = { 9, 10, 12, 15, 20, 35, 50 };
int e [7] = { 3000, 2500, 1500, 1000, 400, 100, 25};
for (i = 0; i < 7; i++ )
{ total salary += s [i]; }
avg salary = total salary / 7.0;
for ( i= 0; I < 7; i++ )
{ if ( s [i] < avg salary ) below += e [i];
else above += e [i];
}
for ( i= 0; i < 7; i++ )
{ total += s [i] * e [i];
total emp = e [i];
}
avg = (float) total / total emp ;
cout << “avg salary =” << avg salary;
cout << “the number of employees below level =” << below;
cout << “the number of employees above level =” << above;
cout << “individual avg” << avg;
}
4. Write a program which finds the mean of the elements of an array, and the element of the array furthest in
absolute value from the mean. Eg. If the array elements are -4, 0, 5, -1, 10, 3, 4, 1, 2, 4
The element 10 is furthest from the mean.
# include <iostream.h>
# include < math.h>
void main ( )
{ int I, float d, f, sum = 0; float mean;
int A [10] = { -4, 0, 5, -1, 10, 3, 4, 1, 2, 4};
for ( i = 0; i < 10; i++ )
{ if (d < fabs (mean – A [i]) )
{ d = fabs (mean – A [1]) );
f = A [i];
}
}
cout << “farthest =” << f;
cout << “abs value =” << mean;
}
int x, temp, l;
x = n;
while ( x > 0 )
{ l = 0;
for ( i = 0; i < x – 1; i++ )
{
if ( A [i] > A [ i + 1] )
{ temp = A [i];
A [i] = A [ I + 1];
A [ i + 1] = temp;
l =i + 1;
}
}
x = 1;
}
}
7. List an integer array with n elements. By using linear search, write a program to search a number in that
array. Display “Found” if the search number is found or display “Not found” if the search number is not
found.
# include <iostream.h>
void main ( )
{
int A [100], n, num, found = 0;
cout << “How many numbers”
cin >> n;
for (int i = 0;i < n; i++ )
{
cout << “Enter number”;
cin >> A [i];
}
cout << “Enter search number”;
cin >> num;
i=0
while (i < && ! found )
{ if ( num == A [i] ) found = 1;
else i++ ;
}
if (found)
cout << “Found”;
else cout << “Not Found”;
}
8. List an integers array with n elements and write a program to search a number in that array by using
binary search method. Display a “Found” if the search number is found or display “Not found” if it is not
found.
# include <iostream.h>
void main ( )
{ int A [100], num, n, f, l, M;
cout << “Enter how many numbers”;
17
cin >> n;
for ( i = 0; i < n; i++ )
{ cout << “Enter search number”;
cin >> num;
f = 0;
l = n – 1;
while ( f <= 1 && !found )
{ M = (f + i )/ 2 ;
if ( num == A [M] )
found = 1;
else if ( num > A [M] )
f = M + 1;
else l = M – 1;
}
if (found) cout << “Found”;
else cout << “Not Found”;
}
18
Chapter (11)
1. Write a program to create “student.dat” file which includes roll number and the marks of three subjects.
Prompt the user “Any more data (Y/N)?” to continue or not.
3. Write a program to create a text file which includes the ASCII characters table.
# include <stdio.h>
# include <conio.h>
# include < ctype.h>
void main ( )
{
int i, ascii;
FILE * fp;
fp = fopen ( “ASCII-tab.sat”’ “w+” );
for (i = 0; i < 256; i++ )
19
{
ascii = toascii (i);
fprintf (fp, “%c”, ascii );
}
getch ( );
fclose (fp);
}
4. Write a program to create a text file which has the multiplication tables.
(From 1 to 16 multiplication tables.)
# include <iostream.h>
# include < conio.h>
void main ( )
{
int i, j, ans;
FILE * fp;
fp = fopen ( “Mul-Tab.dat”, “w+” );
for (i = 1; i <= 16; i ++ )
for ( j = 1; j <= 12; j++ )
{
ans =i * j ;
fprintf ( fp, “ %d * %d = %d \n”, i, j, ans );
}
getch ( );
fclose (fp);
}
20
Part (2)
Chapter (2)
Objects And Classes
1. Create a class that imitates part of the functionality of the base data type int. Call the class Int. The
only data in this class is an int variable. Include member functions to initialize an int to 0, to initialize it to an
int value, to display it, and to add two Int values. Write a program that exercises this class by creating two
initialized Int values, adding these two initialized values, adding these two initialized value and placing the
respond in the un-initialized value, and then display this result.
2. Imagine a tollbooth at a bridge. Cars passing by the booth are expected to pay a fifty cent toll. Mostly they
do, but sometimes a car has goes by without paying. The tollbooth keeps track of the number of cars that
hours gone by, and of the total amount of money collected. Model this tollbooth with a class called
tollbooth. The two data items are a type unsigned int to hold the total number of cars, and a type double to
hold the total amount of money collected. A constructor initializes both these two to 0. A member function
called paying-car ( ) increments the car total and add 0.50 to the cash total. Another function called nopay-
car ( ) increments the car total but adds nothing to the cash total. Finally a member function called
display ( ) displays the two totals.
tollbooth ( )
{ total cars =0; total cash = 0.0;}
void payingcar ( )
{
total cars + +; total cash + = Tolls ;}
void nopaycar ( )
{
total cars ;}
++
void display ( )
{ cout<< “\n cars = ” << total cars;
cout << “\n cash = ” << total cash;
}
};
void main ( )
{ tollbooth booth;
char ch;
cout<< “\n Press 0 for each no paying car ”;
cout<< “\n Press 1 for paying car ” ;
cout << “\n Press 2 for to exist the paragraph ” ;
do { ch = getdch ( );
if (ch = = ‘0’, booth . nopay car ( );
if ( ch = = ‘1’, booth . nopay car ( );
} while (ch ! = ‘2’ );
booth display ( ); getch ( );
3. Create a class called time that has separate int member data for hours, minutes and seconds. One
constructor should initialized those data to 0, and another should initialize it to fixed values. A member
function should display it, in 11:59:59 format. The final member function should add two objects of type
time passed as arguments. A main program should create two initialized time objects, and one that isn’t
initialized. Then it should add the two initialized values together, leaving the result in the third time variable.
Finally it should display the value of third variable.
4. Create a class called Distance that include two data items (int feet and float and float inches) and include
member functions to initialize data, getdists function, showdist functions and add functions for two Distance
objects. Write a program that exercise this class and display the three distance objects.
* include <iostream.h>
* include <conio.h>
class Distance
{
private:
int feet;
float inches;
public:
Distance( ) { feet= 0; inches= 0.0}
Distance ( int ft, float in) { feet=ft inches = in; }
void getdist( )
{
cout << “ \n Enter feet:’’; cin>> feeet;
cout << “ \n Enter inches:” cin>> inches;
}
void showdist ( )
{ cout << feet << “ \’ - ”<< inches<< ‘\’’’;}
void add-dist ( Distance d1, Distance d2);
};
void Distance :: add-dist ( Distance d1, Distance d2);
};
void Distance:: add-dist ( Distance d1, Distance d2)
{
inches= d1. inches +d2. inches;
if ( inches >=0)
{ inches - = 12.0; feet + +; }
feet + = d1 .feet +d2. feet;
}
Int obj 1 ( 33);
23
Chapter (3)
Arrays and Strings
1. A stack is a data storage device that are the last item stored is the first retrieved. Write a program to test
input and output of the stack. (20 marks)
void pop ( )
{ cout << st [ top -- ] ; }
};
void main ( )
{ stack s ;
S. puch ( 11 );
S. puch ( 22 );
S. puch ( 33 );
S . pop ( );
S . pop ( );
S . pop ( );
}
void main ( )
{ string S1 ( “HELLO”);
string S2 ( “HLa HLa”);
string S3 ;
S3 = S1 ;
S3 = concat ( S2 );
S3 = show ( );
2. Create string class that include a string str (an array of char) to concat of two string and test it.
(20 marks)
3. Write a function called reversit ( ) that reverses a string (an array of char). Use a for loop that swaps a
string firs and last characters, and so on. The string should be passed to reversit ( ) as an argument. Write a
program to exercise reversit ( ). The program should get a string from the user call reversit ( ), and print out
the result. Use an input method that allows embedded blanks. (20 marks)
25
4. Create a class called employee that contains a name (an array of char) and employee member (long).
Include a member function called getdata( ) to get data from the user and another function called putdata ( )
to display the data. Write a main ( ) program to exercise this class. It should create an array of type
employee and then input 100 employee. Finally it should print out the data for all the employees.
(20 marks)
# include <iostream.h>
# include <conio .h>
class employee
{
private :
char name [20];
long eno;
public:
void getdata( )
{
cout<< “ \n Enter employee name.”;
cin.getline (name ,20);
cout<< “ \n Enter employee number;”
cin>>eno;
}
void putdata( )
{
cout<< “ \n Employee name:”<<name;
cout<< “ \n Employee number;”<<eno;
}
26
}
void main( )
{
employee e[100];
int I;
for (i=0;i<100;i+ +)
{
cout<< “ \n Enter employee name and number”;
e[i].getdata( );
}
for(i=0;i<100;i + +);
{
cout<< “\n Employee name and number: \n”;
e[i].putdata( );
}
getch( );
}
5. Write a program that calculates the average of up to 100 English distance class as example in this chapter
to calculate the average, use the member function disadd ( ) that adds the total distance and distdiv ( ) that
divided the total distance object by integer (number of distances). (20 marks)
# include<iostream.h>
# include<conio.h>
class distance
{
private;
int feet;
float inches;
public;
distance ( )
{ feet =0; inches =0.0;}
Distance ( int ft,float in)
{feet = ft; inches = in;}
void getdist( )
{
cout<< “ \nEnter feet and inches”;
cin>>feet>>inches;
}
void showdist( )
{
cout<<feet<< “\ “-”<<inches<< “\””;
}
void disadd(distance d)
{
inches = inches + d. inches;
iff(inches> = 12.0)
{ inches - = 12.0;feet+ +;}
feet+ = d.feedt;
}
void distdiv(distance s,int n)
27
}
avg.distdiv(sum,n);
cout<< “\n Sum of distance =”:sum.showdist( );
cout<< “\n Average of distance =”;avg.showdist( );
getch( );’
}
6. A queue is a data storage divide like a stack. The difference is that in a stack the last data item stored is
the first one retrieved, while in a queue the First data item stored is the first retrieved. Use two pointers,
FRONT for retrieve and RARE for entry. The member function push ( ) should include overflow checking
and pop ( ) should include underflow checking. Write a main ( ) program to implement a queue and test it.
# include<iostream.h>
# include<conio.h>
cnst int max = 20;
class queue
{
private;
int q[max], FRON,RARE;
public;
queue( )
{ FRONT =RARE =-1;}
void push(int d)
{
if(RARE<max-1)
q[+ +RARE] =d;
else cout<< “Overflow”;
}
void pop( )
{
if(FRONT<RARE)
cout<< “\n”<<q[+ +FRONT];
else cout<< “Underflow”;
}
};
28
void main( )
{
queue q;
clrscr( );
q.push(11);
q.push(33);
q.pop( );
q.pop( );
q.pop( );
getch( );
}
29
Chapter (4)
Operator Overloading & Data Types Conversion
1. To the Distance class, add on overloaded operator that subtracts two distance like dist 3 = dist 1 – dist 2.
Assume that operator will never be used to subtract a longer number from a smaller one. (20 marks)
# include<iostream.h>
# include<conio.h>
class Distance
{
private;
int feet;
float inches;
public:
Distance( )
{ feet =0; inches = 0.0;}
Distance(int ft ,float in)
{feet = ft;inches = in;}
void getdist( )
{
cout<< “\nEnter feet and inches”;
cin>>feet>>inches;
}
void showdist( )
{
cout<<feet<< “\ “-”<<inches<< “\””;
}
Distance operator-(Distance d1)
{
int f = feet-d1.feet;
float I =inches-d1.inches;
if(i<0)
return Distance(f,i);
}
};
void main( )
{
Distance dist1(11,6.25);
Distance dist2.dist3;
dist2.getdist( );
dist3 =dist1 –dist2;
cout<< “\ndist1 =”;dist1.showdist( );
cout<< “\ndist2 =”;dist2.showdist( );
cout<< “\ndist3 =”;dist3.showdist( );
getch ( );
}
30
2. To the Distance class, added an overloaded operator that add two distance like dist 3 = dist 1 + dist 2.
(20 marks)
#include<iostream.h>
#include<conio.h>
class Distance
{
private;
int feet;
float inches;
public;
Distance( )
{ feet = 0;inches = 0.0;}
Distance(int ft,float in)
{ feet = ft;inches =in;}
void getdist( )
{
cout<< “\nEnter feet and inches”;
cin>>feet>>inches;
}
void showdist( )
{
cout<<feet<< “\ “-”<<inches<< “\””;
}
Distance operator +(Distance d1)
{
int f = feet +d1.feet;
float I = inches + d1.inches;
if(i> =12.0)
{i- =12.0; f + +;}
return Distance(f,i);
}
};
void main( )
{
Distance dist1 (11,6.25);
Distance dist2 .dist3;
dist2.getdist( );
dist3= dist1 + dist3;
cout<< “\ndist1=”;dist1.showdist( );
cout<< “\ndist2 =”;dist2.showdist( );
cout<< “\ndist3 =”;dist3.showdist( );
getch ( );
}
31
3. To the Distance class, add an overloaded operator that add two distance like dist 1 += dist 2. (20 marks)
#include<iostream.h>
#include<conio.h>
class Distance
{
private;
int feet;
float inches;
public;
Distance( )
{ feet = 0;inches = 0.0;}
Distance(int ft,float in)
{ feet = ft;inches =in;}
void getdist( )
{
cout<< “\nEnter feet and inches”;
cin>>feet>>inches;
}
void showdist( )
{
cout<<feet<< “\ “-”<<inches<< “\””;
}
void operator += (Distance d1)
{
feet +=d1.feet;
inches += d1.inches;
if ( inches>= 12.0)
{
inches - = 12.0;
feet ++;
}
};
void main( )
{
Distance dist1( 11,6.25);
Distance dist2;
cout<< “\n dist1=”;
dist1.showdist( );
dist2.getdist( );
dist1+ = dist2;
cout <<”\n dist1=”;
dist1.showdist( );
cout <<”\n dist2=”;
dist2.showdist( );
getch( );
}
32
4. To the Distance class, add an overloaded operator that dis1 < dist2. (20 marks)
#include<iostream.h>
#include<conio.h>
enum Boolean {false , true};
class Distance
{
private:
int feet;
float inches;
public;
Distance( )
{ feet = 0;inches = 0.0;}
Distance(int ft,float in)
{ feet = ft;inches = in;}
{
cout<< “\nEnter feet and inches”;
cin>>feet>>inches;
}
void showdist( )
{
cout<<feet<< “\ “-”<<inches<< “\””;
}
Boolean operator<(Distance d1)
{
float f1 = feet + inches/12;
float 12 = d2.feet + inches/12;
return (f1<f2)? true:false;
}
};
void main( )
{
Distance dist;
dist1. getdist( )
Distance dist2(6,2.5);
cout<< “\ndist1 =”;dist1.showdist( );
cout<< “\ndist2 =”;dist2.showdist( );
if(dist1<dist2)
cout<< “Dist1 is less than Dist2”;
else cout<< “Dist2 is greater than Dist1”;
getch ( );
}
33
5. Write a program the conversion of distance to meter, meter is Distance. (20 marks)
#include<iostream.h>
const float MTF = 3.280833;
class Distance
{ private : int ft;
float in;
public : Didtance ( )
{ft.in = 0;}
Distance ( int f, float i)
{ ft = f;
in = I;}
void show ( )
{ cout<<ft<< “\’”<<in<< “\” ”; }
Distance ( float m)
{ float f = m * MTF;
ft = f;
in = ( f- ft)*12; }
Operator Float ( )
{ Float f = ft + in/12;
Float m = f / MTF ;
return m;}
};
void main ( )
{ Distance d ( 5,5.5);
float m;
cout<< “ meter =”<<m;
cout<< “ Enter meter”;
cin>> m;
d = m;
d.show ( );
}
6. Create a polar class that contain radius and angle and Rec class that contsin x co, y co. Write a program to
converts from polar to Rec using routine in source. (20 marks)
#include<math.h>
#include<iostream.h>
class Rec
{ private : double xco,yco;
public : Re( c )
{ xco = 0; yco= 0;}
Rec ( double x , double y)
{ xco = x;
yxo = y;}
void get ( )
{ cout<< “Enter xco & yco”;
cin>>xco>>yco;}
};
34
class Polar
{ private : double radius,angle;
public : Polar ( )
{ radius = 0.0;
angle = 0.0;}
Polar (double r, double a)
{ radius = r;
angle = a;}
void get ( )
{ cout<< “Enter radius & angle”;
cin>>radius>>angle;}
void show ( )
{ cout<<radius<< “\ t”<<angle;}
operator Rec ( )
{ double a,b;
a = radius *cos ( angle);
b = radius*sin (angle);
return Rec (a,b);}
};
void main ( )
{ Polar P;
Rec R;
P.get ( );
R =P;
R.show ( );
};
7. Create a polar class that contain radius and angle and Rec class that contsin x co, y co. Write a program to
converts polar to Rec using conversion routine in destination. (20 marks)
#include<math.h>
#include<iostream.h>
class Polar
{
Private : double radius, angle;
public : Polar ( ) { }
Polar ( double r, double a)
{ radius = r;
angle = a;}
void get( )
{ cout<< “Enter radius & angle”;
cin>>radius>>angle;
void show ( )
{ cout<<radius<< “ \ t”<<angle;}
double get r ( )
{ return radius;}
double get a ( )
{ return angle;}
};
35
8. Create the time class with integer members (hours, minutes, seconds) and include overloaded increment
(++) and decrement (--) operators that operate in both prefix and postfix notation and return value. Write a
main program to test the above time calss. (20 marks)
#include<iostream.h>
#include<conio.h>
class time
{
private:
int hr.min.sec;
public:
time( )
{ hr = 0;min =0;sec = 0;}
time(int h,int m, int s)
{ hr =h;min = m;sec =s;}
void gettime ( )
{
cout<< “\nEnter hour,minute and second”;
cin>>hr>>min>>sec;
}
void puttime ( );
time operator + +( )
{
+ + sec;
return time (hr,min,sec);
}
time operator+ +( )
36
{
- - sec;
return time(hr,min,sec);
{
sec - -
return time(hr,min,sec);
}
};
void time::puttime ( )
{
if(see<= -1)
{sec+ = 60;
min--;
if(min< = -1) {
min+=60;
hr--;
}
}
if(sec>=60)
{sec-=60;
min+ +;
if(min>=60)
{min-=60;
hr++;}
}
void main( )
{
time t1(5,59,59);
time t2(10,10,10);
time t3,t4;
13=t1++ ;
14 = ++t1;
cout<< “time 3 =”:t3.puttime( );
cout<< “time 4 =”:t4.puttime( );
13=t1 --;
14 =--t1;
cout<< “time 3 =”:t3.puttime( );
cout<< “time 4 =”:t4.puttime( );
getch( );
}
37
9. Create a class Int that contain an integer variable. Overload all five integer arithmetic operators (+, -, *, /,
%). So that they operate an object of type Int. If the result of any such operation exceeds the normal range of
int from -32768 to 32767, the operator prints a warning and terminate the program. Write a program to test
this class.
(20 marks)
# include <iostream.h>
# include <conio.h>
# include <stdio.h>
class int
{
private :
int a;
public :
int ( )
{a = 0; }
int (int x)
{ a = x; }
void getdata ( )
{ cout << “\n Enter an integer number”;
cin >> a;
}
void putdata ( )
{
cout << “The Result =” << a;
}
int check (long y)
{ if ( y >= -32768 && y < 32768 )
return 1;
else return 0;
}
int operator + (int i)
{
long y = long (a) + long (i.a);
if check(y) return int(y);
else {
cout << “Over Range”;
exit (0);
}
}
int operator – (int i)
{
long y = long (a) – long (i.a);
if check(y) return int(y);
else {
cout << “Over Range”;
exit (0);
}
}
38
10. Create the polar class to incorporate overloaded operators for multiplication and division that require a
constant (type double) as the second operand, not a polar. Write a program to exercise all these operations
with a variety of values. ( 20
marks)
# include <iostream.h>
class polar
{ private : double radius, angle;
public : polar ( )
{ radius = angle = 0.0; }
Polar (double r, double a)
{ radius = r;
angle = a;
}
void get ( )
{ cout << “Enter radius & angle”;
cin >> radius >> angle;
}
void show ( )
{ cout << radius << “\t” << angle; }
Polar operator * (double x)
{ return polar (radius * x, angle); }
Polar operator / (double x)
{ return polar (radius/x, angle); }
};
void main ( )
{ Polar P;
P.get ( );
double x;
cout << “Enter Multiplication number”;
cin >> x;
P=P*x;
cout << “Multiplication =” ;
P.show ( );
cout << “Enter division number”;
cin >> x;
P = P/x ;
cout << “Division”;
P.show ( );
}
40
Chapter-5
Inheritance
Class Scientist
Class manager Class laborer
title; publications
dues;
# include <iostream.h>
# include <string.h>
# define max 20
class employee
{ protected : char name [max];
long num;
public : employee ( )
{ name [0] = ‘\0’;
num = 0.0;
}
employee (char s[ ], long n)
{ stcpy (name, s);
num = n;
}
void get ( )
{ cout << “enter name”;
cin.get (name, max)
cout << “Enter number”;
cin >> num;
}
void show ( )
{ cout << “\n Name =” << name;
cout << “\n Number =” << num;
}
};
41
# include <iostream.h>
# include <string.h>
# define max 20
class employee
{ protected : char name [max];
long num;
public : employee ( )
{ name [0] = ‘\0’;
num = 0.0;
}
employee ( char n [ ], long n )
{ strcpy (name, n);
num = n;
}
void get ( )
{ cout << “Enter name” ;
cin.get (name, max);
cout << “Enter number”;
42
3. Create a student class that includes the member data number (int) and marks of four papers (ints). The
member function are get-student ( ) to get student data and display ( ) to display the object details. The grade
class also include the member data roll number (int) and grade value (char) and the member function where
a conversion function from student class to grade class and a display function. The conversion condition are
as follow:
(i) Average of paper marks >= 75, grade = ‘A’
(ii) Average of paper marks < 75 and >= 65, grade ‘B’
(iii) Average of paper marks < 65 and > -40, grade ‘C’
Write a program to create two different objects and test the conversion.
(20
marks)
# include <iostream.h>
class student
{ private : int rno, m1 , m2 , m3 , m4 ;
public : void get ( )
{ cout << “Enter rno and marks”;
cin >> rno >> m1 >> m2 >> m3 >> m4 ;
}
void show ( )
{ cout << rno << “\t” << m1 << “\t” << m2 <<“\t”
<< m3 << “\t” << m4 ;
}
int getrno ( )
{ return rno; }
int get m1 ( )
{ return m1 ; }
int get m2 ( )
{ return m2 ; }
int get m3 ( )
{ return m3 ; }
int get m4 ( )
{ return m4 ; }
};
class grade
{ private : int r;
char gvalue;
public : void get ( )
{ cout << “Enter rno & gvalue”;
cin >> r >> gvalue;
}
void show ( )
{ cout << r << “\t” << gvalue; }
grade ( student st )
{ int P1 , P2 , P3 , P4 ;
r = st. getrno ( );
P1 = st.getm1 ( );
P2 = st.getm2 ( );
P3 = st.getm3 ( );
P4 = st.getm4 ( );
float avg = ( P1 + P2 + P3 + P4 ) /4 ;
45
4. Create the Type class which store dimension (string) grade (string) and Distance class which store ft (int),
in (float). From the type and Distance class derived class called lumber that contain qty (int) price4 float.
Implement main program and test it. (20 marks)
# include <iostream.h>
# include < string.h>
const int max = 40;
class Type
{ private : char dimensions [max];
char grade [max];
public : Type ( )
{ strcpy ( dimensions, “N/A” );
strcpy ( grade, “N/A” );
}
Type ( char di[ ] , char gr[ ] )
{ strcpy ( dimension, di);
strcpy (grade, gr);
}
void get type ( )
{ cout << “\n Enter dimensions (2 * 4 etc):”;
cin >> dimensions;
cout << “\n Enter grade (rough-cut, construction-
grade, surface-four-sides,)” ;
cin >> grade;
}
void show type ( )
{ cout << “\n Dimensions =” << dimensions;
cout << “\n Grade=” << grade;
}
};
class Distance
{ private : int feet;
float inches;
public : Distance ( )
{ feet = 0; inches = 0.0; }
46
void showdist ( )
{ cout << feet << “\’-” << inches << ‘\”’; }
};
class lumber : public Type, public Distance
{ private : int quantity;
float price;
public : lumber ( ), Type ( ), Distance ( )
{ quantity = 0; price = 0.0; }
lumber ( chart di[ ], char gr[ ], int ft, float in,
int qu, float prc);
Type (di, gr), Distance (ft, in)
{ quantity = qu ; price = prc; }
void getlumber ( )
{ Type : : gettype ( );
Distance : : getdist ( );
cout << “\n Enter quantity:”; cin >> quantity;
cout << “\n Enter price:”; cin >> price;
}
void showlumber ( )
{ Type : : showtype ( );
Distance : : showdist ( ) ;
cout << “\n Price for:” << quantity << “is $”
<< quantity * price;
}
};
void main ( )
{ lumber siding;
cout << “\n Siding Data : \n”;
Siding.getlumber ( );
lumber studs ( “2*4”, “constru”, 8, 0.0, 200, 4.45 );
cout << “\n siding”; siding.showlumber ( );
cout << “\n studs”; studs.showlumber ( );
}
5. Create a class publication that stores the title ( a string ) and price (type float). From this class derive two
classes: book which adds a page count (type int) and tape, which adds a playing time in minutes (type float).
Each of these three classes should have a getdata ( ) function to get is data from the user and a putdata ( )
function to display its data. Write a main ( ) program to implement this class. (20 marks)
47
# include <iostream.h>
# include <string.h>
# define max 20
class publication
{ protected : char title [max];
float pri;
public : void get ( )
{ cout << “Enter title”;
cin.get (title, max );
cout << “Enter price”;
cin >> pri;
}
void show ( )
{ cout << “\n Title =” << title;
cout <, “\n Price =” << pri;
}
};
class book : public publication
{ private : int pcount;
public : void get ( );
{ publication : : get ( );
cout << “Enter page count”;
cin >> pcount;
}
void show ( )
{ publication : : show ( );
cout << “\n Page Count =” << pcount;
}
};
class type : public publication
{ private : float min;
public : void get ( )
{ publication : : get ( )
cout << “Enter minute” ;
cin >> min;
}
void show ( )
{ publication : : show ( );
cout << “\n Minute =” << min;
}
};
void main ( )
{ book b;
tape t;
b.get ( );
b.show ( );
t.get ( );
t.show ( );
}
48
6. Create a class publication that stores the title (string) and price (float) and sale class that holds an array of
three floats so that it can record the dollar sale of a particular publication for the last three month. The book
and tape classes so they are derived from both publication and sales. Write a main program to create a book
object and tape object and exercise their input/output capabilities. (20 marks)
# include <iostream.h>
# define max 20
class publication
{ protected : char title [max];
float pri;
public : void get ( )
{ cout << “Enter title”;
cin.getline (title, max);
cout << “Enter price”;
cin >> pri;
}
};
class sale
{ protected : float m [3];
public : void get ( );
void show ( );
};
void sale :: get ( )
{ for (int i = 0 ; i < 3; i++)
{ cout << “Enter sale amount for one month”;
cin >> m [i];
}
}
void sale : : show ( )
{ for ( int i = 0; i < 3; i++ )
{ cout << m[i]; }
}
class book : public publication, public sale
{ private : int pcount;
public : void get ( )
{ publication : : get ( );
sale : : get ( );
cout << “Enter page count”;
cin >> pcount;
}
void show ( )
{ publication : : show ( );
sale : : show ( );
cout << “\n Page Count =” << pcount;
}
};
class tape : public publication, public sale
{ private : int min;
public : void get ( )
49
{ publication : : get ( );
sale : : get ( );
cout << “Enter minute”;
cin >> min;
}
void show ( )
{ publication : : show ( );
sale : : show ( );
cout << “Minute =” << min;
}
};
void main ( )
{ book b;
tape t;
b.get ( );
b.show ( );
t.get ( );
t.show ( );
}
7. A company rents both cars and trucks. A class transport stores the capacity (int), the status (rented as
available) and the cost of rental ( a float). From this class three count ( an int); and truck which adds a load
limit measured in matric tones (an int). Each of these three classes should have a getdata ( ) function to
obtain data from user and a showdata ( ) function to display data on the screen. Implement these three
classes and write a main ( ) program to test a car and truck classes.
# include <iostream.h>
# define max 5
class transport
{ protected : int cop;
char status [max];
float cost;
public : void get ( )
{ cout << “Enter capacity”;
cin >> cap;
cout << “Enter status”;
cin.get (status, max);
cout << “Enter cost”;
cin >> cost;
}
void show ( )
{ cout << “\n Capacity =” << cap;
cout << “\n Status =” << status;
cout << “\n Cost =” << cost;
}
};
class car : public transport
{ private : int no: per; int count;
50
8. Create a class publication that stores the title (string) and price (float) and sale class that holds an array of
three float. The book and tape that they are derived from publication and sale. Add a disk class that like
book and tape, is derived from publication. The disk class should incorporate the same member functions as
the other classes. The data item unique to this class is the disk size: either 3-1/2 inches or 5-1/4 inches. You
can use an enum Boolean type to store this item, but the complete size should be displayed. The user could
select the appropriate size by typing 3 or 5.
# include <iostream.h>
# define max 20
class publication
{ protected : char title [max];
51
float pri;
public : void get ( )
{ cout << “Enter title”;
cin.get (title, max);
cout << “enter price”;
cin >> pri;
}
void show ( )
{ cout << “\n Title =” << title;
cout << “\nPrice =” << pri;
}
};
class sale
{ protected : float m[3];
public : void get ( );
void show ( );
};
void sale : : get ( )
{ for (int i = 0; i < 3; i++ )
{ cout << “Enter sale amount for one month”;
cin >> m[i];
}
}
void sale : : show ( )
{ for (int i = 0; i < 3; i++ )
{ cout << m[i]; }
}
class book : public publication, public sale
{ private : int pcount;
public : void get ( )
{ publication : : get ( );
sale : : get ( );
cout << “Enter page count”;
cin >> pcount;
}
void show ( )
{ publication : : show ( );
sale : : show ( );
cout << “\n Page count =” << pcount;
}
};
class tape : public publication, public sale
{ private : int min;
public : void get ( )
{ publication : : get ( );
sale : : get ( );
cout << “Enter Minute”;
cin >> min;
}
void show ( )
52
{ publication : : show ( );
sale : : show ( );
cout << “\n Minute =” << min;
}
};
enom size { three, five };
class disk : public publication
{ private : size s;
public : void get ( )
{ int n;
cout << “Enter 3 or 5”;
cin >> n;
s = ( n = = 3 ) ? three : five;
publication : : get ( );
}
void show ( )
{ cout << ( s = = three ) ? “disk size = 3 ½”;
“disk size = 5 ¼”;
publication : : show ( );
}
};
void main ( )
{ book b;
tape t;
disk d;
b.get ( ); b.show ( );
t.get ( ); t.show ( );
d.get ( ); d.show ( );
}
9. Start with the publication, book and tape classes. Suppose you want to add the date of publication for both
books and tapes. From the publication class, derived a new class so called publication 2 that includes this
member data. Then change book and tape so they are derived from publication 2 instead of publication.
Make all the necessary changes in member functions to the user can input and output data along with the
other data. For the data class, use three ints of months, day and year. The member functions are getdata ( )
and showdata ( ).
# include <iostream.h>
# define max 20
class publication
{ protected : char title [max];
float pri;
public : void get ( )
{ cout << “enter title”;
cin.get (title, max);
cout << “Enter price”;
cin >> pri;
}
void show ( )
{ cout << “\n Title =” << title;
53
Chapter (6)
Pointers
1. Create a linklist program using pointer. Add a destructor to the linklist program. It should delete all the
links when a linklist object is destroyed. It can to this by following along the chain, deleting each link as it
goes. You can test the destructor by having it display a message each time it deletes a link; it should delete
the same number of links that were added to the list. (20 marks)
# include <iostream.h>
struct link
{ int data;
link * next;
};
class linklist
{ private : link * F;
public : linklist ( )
{ F = NULL; }
void add ( int d );
void display ( );
~ linklist ( );
};
void linklist : : add ( int d )
{ link * L;
L = new link;
L data = d ;
L next = F;
F = L;
}
void linklist : : display ( )
{ link * c;
c = F;
while ( c! = NULL )
{ cout << c data;
c = c next;
}
}
linklist : : ~ linklist ( )
{ link * d ;
d = F;
while ( d ! = NULL )
{ F = d next;
delete d;
d = F;
}
}
void main ( )
{ linklist li;
Li.add (5);
Li.add (6);
Li.display ( );
55
}
2. Modify the person class in the presort program so that it include not only a name but also a salary item of
type float representing the person’s salary. You will need to change the getname ( ) and putname ( ) member
functions to getdata ( ) and putdata ( ). You will also need a getsalary ( ) function. Using pointer notation,
write a slasort ( ) function that sorts the pointers in the persptr array by salary rather than name. (20 marks)
# include <iostream.h>
# define max 20
Class person
{ private : char name [max];
float salary;
Public : void get ( )
{ cout << “Enter name”;
cin.get ( name, max );
cout << “Enter salary”;
cin >> salary;
}
void show ( )
{ cout << “\n Name =” << name;
cout << “\n Salart =” << salary;
}
float getsalary ( )
{ return salary; }
};
void main ( )
void bsort ( Person ** PP, int n );
Person * P[100]; int n = 0;
do { P[n] = new Person;
P[n] get ( );
n++ ;
} while ( n < 100 );
cout << “Unsorted list”;
for ( int i= 0; i < n; i++ )
{ P[i] show ( ); }
bsort ( P, n)
cout << “Sorted list”;
for ( int i = 0; i < n; i++ )
{ P [i] show ( ); }
}
void bsort ( Person ** PP, int n )
{ void order ( Person ** PP1 , Person ** PP2 );
for ( int i = 0; i < n-1; i++ )
{ for ( int j = i + 1; j < n; j++ )
{ order ( PP + i , PP + j ); }
}
}
void order ( Person ** PP1 , Person ** PP2 )
{ if ( * PP1 getsalary ( ) > * PP2 getsalary ( ) )
{ Person * temp;
temp = * PP1; * PP1 = *PP2 = temp;
}
56
}
3. Revise the additem ( ) member functions from the linklist program so that it adds the item at the end of
the list, rather than the beginning. This will cause the first item inserted to be the first item displayed. To add
the item you will need to follow the chain of pointers to the end of the list, then change the last link to point
to the new link. (20 marks)
# include <iostream.h>
struct link
{ int data;
link * next;
};
class linklist
{ private : link * F
public : linklist ( )
{ F = NULL; }
void add ( int d );
void display ( );
void operator = (linklist L1 );
~ linklist ( );
};
void linklist : : add ( int d )
{ link * L;
L = new list;
L data = d;
L next = NULL;
if ( F == NULL )
{ F = L; }
else { link * P ;
P = F;
while ( P next != NULL )
{ P = P next; }
P next = L;
}
void linklist : : display ( )
{ link * c ;
c = F;
while ( c != NUL )
{ cout << c data;
c = c next;
}
}
void linklist : : operator = ( linklist L1 )
{ link * t, * temp, * P;
L = F;
while ( t != NULL )
{ temp = new link;
temp data = t data;
temp next = NULL;
if ( F = = NULL )
57
{ F = temp;
P = temp;
t = t next;
}
else { P next = temp;
P = temp;
t = t next;
}
}
}
linklist : : ~ linklist ( )
{ link * d ;
D = F;
while ( d ! = NULL )
{ F = d next;
delete d ;
d = F;
}
}
void main ( )
{ linklist L1 , L2 ;
L 1.add (5);
L1 .add (6);
L 1. add (7);
L 1.display ( );
L 2 = L2 ;
L 2. display ( );
}
4. Create an employee class that certain name, number and student class that holds school, degree, the
manager class that are derived from employee and student’s class. That certain title (string), class (double).
From the manager class derive a class called executive. The additional data in executive class will be the
size of the employee’s yearly bonus and the number of shares of company stock held in his or her stock
option plan. Add the appropriate member functions so these data items can be input and display along with
the other manager data.
# define max 20
# include <iostream.h>
# include <string.h>
class employee
{ protected : char name [max];
long num;
public : employee ( ) { }
employee (char n[ ], long n)
{ strcpy ( name , n )
num = n;
}
void get ( )
{ cout << “Enter name”;
58
Chapter (7)
Virtual and Friend Functions
1. Imagine the publication company. Write a main ( ) program that creates an array of pointers to
publication. This is similar to virtpers. In a loop ask the user for data about a particular book or tape, and use
new to create an object of type book or tape to hole the data. Put the pointer to the object in the array. When
the user has finished entering data for all books and tapes, display them. (20 marks)
# include <iostream.h>
# define max 20
class publication
{ protected : char title [max];
float price ;
public : void get ( )
{ cout << “Enter title”;
cin.get ( title, max );
cout << “Enter price”;
cin >> price;
}
virtual void show ( )
{ cout << “\n Title =” << title;
cout << “\n Price =” << price;
}
};
class book : public publication
{ private : int pcount;
public : void get ( )
{ publication : : get ( );
cout << “Enter page count”;
cin >> pcount;
}
void show ( )
{ publication : : show ( );
cout << “\n Page count =” << pcount;
}
};
class tape : public publication
{ private : int min;
public : void get ( )
{ publication : : get ( );
cout << “Enter minute”;
cin >> min;
}
void show ( )
{ publication : : show ( );
cout << “\n Minute =” << min;
void main ( )
{ publication * P [100];
book * b; int n = 0;
61
2. In the distance class, create an overloaded * operator so that two distances can be multiplied together.
Make it a friend function so that you can use such expression like as
dist 1 = 7.5 * dist 2 ;
You will need a one-argument constructor to convert floating point values into distance value. Write a main
program to test this operator.
(20
marks)
# include <iostream.h>
class Distance
{ private : int ft;
float in;
public : Distance ( )
{ ft = 0; in = 0.0; }
Distance ( int f, float i )
{ ft = f;
in = i;
}
void get ( )
{ cout << “Enter ft & in”;
cin >> ft >> in;
}
void show ( )
{ cout << ft << “ \’ ” << in << “ \” ”; }
Distance (float f)
{ ft = f;
in = ( f – ft ) * 12;
}
Friend Distance operator * ( Distance d3 , Distance d2 );
};
Distance Distance : : operator ( Distance d3 , Distance d2 )
{ Distance temp;
62
3. Involved adding an overloaded destructor to the link list class. Suppose we fill the class with the
assignment of the entire class such as
List 2 = List 1 ;
Using the operator overloading assignment operator. Write a main ( ) program to implement it.
(20 marks)
Chapter (8)
Files and Streams
1. Start with the Distance class. Using a loop, get a number of distance values from the user and write them
to a disk file. Append them to existing values in the file until no more data will be input. Then read all
objects from file and display them.
# include <iostream.h>
# include <fstream.h>
# include <ctype.h>
# include <conio.h>
class Distance
{ private : int feet;
float inches;
public : Distance ( ) { feet = 0; inches = 0; }
Distance ( int ft, float in ) { feet = ft; inches = in;
void getdist ( )
{ cout << “\n Enter feet :” ; cin >> feet;
Cout << “Enter inches :” ; cin >> inches;
}
void showdist ( )
void main ( )
{ char ch;
Distance dist;
fstream f;
f.open ( “DIS.DAT”, ios : : app , ios : : in );
do
{ cout << “\n Distance”;
dist.getdist ( );
f.write ( (char * ) & dist, size of (dist) );
cout << “Enter another distance ( y/n )?”;
cin >> ch;
}
while ( toupper (ch) = = ‘Y’ );
f.seekg (0);
f.read ( (char *) & dist , size of (dist) );
int count = 0;
while ( !f.eof (,)
{ cout << “\n Distance” << ++ count << “:”;
dist.showdist ( );
f.read ( (char *) & dist, size of (dist) );
}
cout << end 1;
}
65
2. Starting with the link list program, create a program that gives the user four options which can be selected
by pressing a key.
Add a link to the list in memory
Display the data from all the links in memory
Write the data for all the links to a disk file
Read all the data back from the file and construct a new linked list to store them.
# include <iostream.h>
# include <fstream.h>
# include <conio.h>
# include <stdio.h>
# include <ctype.h>
struct node
{ int data ;
node * next;
};
class linklist
{ private : node * first;
public : linklist ( )
{ first = NULL; }
void additem ( );
void display ( );
void diskin ( );
void diskout ( );
~ linklidt ( );
};
void linklist : : additem ( )
{ int num;
cout << “Enter a number”;
cin >> num;
node * newptr = new node;
newptr -> data = num;
newptr -> next = NULL;
if ( first = = NULL )
first = newptr;
else
{ node * ptr;
ptr = first;
while ( ptr -> next != NULL ) ptr = ptr -> next;
ptr -> next = newptr;
}
}
void linklist : : display ( )
{ node * ptr = first ;
while ( ptr != NULL )
{ cout << ptr -> data << “\n”;
ptr = ptr -> next;
}
66
}
linklist : : ~ linklist ( )
{ node * delptr = first;
delptr = first;
cout << “\n Destructor”;
while ( delptr != NULL )
{ first = delptr -> next ;
delptr -> next = NULL;
delete delptr;
delptr = first;
}
delete first;
cout << “\n Finished deletion nodes from the beap”;
void linklist : : diskin ( )
{ fstream f;
f.open ( “LIST.DAT”, ios : : binary \ ios : : in );
if (f)
f.read ( (char *) this, sizeof ( *this ) );
}
void linklist : : diskout ( )
{ fstream f;
f.open ( “LIST.DAT”, ios : : binary \ ios : : out );
f.write ( (char *) this, sizeof (*this) );
}
void main ( )
{ int choice; char and;
linklist l;
do
{ cout << “\n 1.add to memory”;
cout << “\n.Display from memory”;
cout << “\n3.Write to disk file”;
cout << “\n4.Read and new create to disk file;
cout << “\n5.Exit”;
cout << “Enter you choice (1, 2, 3, 4, 5)”;
cin >> choice;
switch (choice)
{ case 1 :
do
{ 1.additem ( );
cout << “Any more (y/n)?” ;
cin >> ans;
}
while ( toupper (ans) = = ‘Y’ );
break;
}
case 2 : L.display ( ); break;
case 3 : L.diskout ( ); break;
case 4 : L.diskin ( );
L.display ( );
cout << “Any more (y/n) ?”;
67