0% found this document useful (0 votes)
120 views

Oop Documents

The document contains solutions to 7 questions involving the use of structures in C++. The questions involve creating structures to store phone numbers with area codes, exchanges, and numbers; points with x and y coordinates; volumes with length, width, and height dimensions; employee data with numbers and compensation; dates with months, days, and years; enumerated types for employee types; and a combined employee structure with number, compensation, type, and hire date. The solutions demonstrate initializing and accessing structure variables, performing calculations with structure members, user input and output of structure data, and other basics of working with structures in C++.

Uploaded by

Dawood
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views

Oop Documents

The document contains solutions to 7 questions involving the use of structures in C++. The questions involve creating structures to store phone numbers with area codes, exchanges, and numbers; points with x and y coordinates; volumes with length, width, and height dimensions; employee data with numbers and compensation; dates with months, days, and years; enumerated types for employee types; and a combined employee structure with number, compensation, type, and hire date. The solutions demonstrate initializing and accessing structure variables, performing calculations with structure members, user input and output of structure data, and other basics of working with structures in C++.

Uploaded by

Dawood
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

UNIVERSITY OF KOTLI (AJK)

Assingnment No.01
Topic: Exercise Chap # 4 & Chap # 5

Class: BS (SE 2nd)

Subject: Object Oriented Programming

Roll No: 24 (Repeater)

Submitted to : Sir Zaheed Ahmad

Submitted by: Dawood Bin Azad

_____________________________________________

Submission date: 09/10/2021


CHAPTER# 4
Q 1. A phone number, such as (212) 767-8900, can be thought of as having three parts: the area code
(212), the exchange (767), and the number (8900). Write a program that uses a structure to store these
three parts of a phone number separately. Call the structure phone. Create two structure variables of type
phone. Initialize one, and have the user input a number for the other one. Then display both numbers. The
interchange might look like this:

Enter your area code, exchange, and number: 415 555 1212

My number is (212) 767-8900

Your number is (415) 555-1212.

Solution:

using namespace std;

struct phone {

int area_code;

int exchange_code;

int number;

};

int main()

phone ph1, ph2;

ph1.area_code = 212;

ph1.exchange_code = 767;

ph1.number = 8900;
cout <<"Enter your area code, exchange and number: ";
cin >>ph2.area_code >>ph2.exchange_code >>ph2.number;

cout <<"My number is: ("<<ph1.area_code <<") " <<ph1.exchange_code <<"-"


<<ph1.number <<endl;

cout <<"Your number is: ("<<ph2.area_code <<") " <<ph2.exchange_code <<"-"


<<ph2.number <<endl;

return 0;

Q 2. A point on the two-dimensional plane can be represented by two numbers: an x coordinate and a y
coordinate. For example, (4,5) represents a point 4 units to the right of the vertical axis, and 5 units up
from the horizontal axis. The sum of two points can be defined as a new point whose x coordinate is the
sum of the x coordinates of the two points, and whose y coordinate is the sum of the y coordinates. Write
a program that uses a structure called point to model a point. Define three points, and have the user input
values to two of them. Then set the third point equal to the sum of the other two, and display the value of
the new point. Interaction with the program might look like this:

Enter coordinates for p1: 3 4


Enter coordinates for p2: 5 7
Coordinates of p1+p2 are: 8, 11
Soution:

#include<iostream>

using namespace std;

struct point {

int x_coordinate;
int y_coordinate;
};

int main()

{
point p1, p2, p3;

cout <<"Enter coordinates for p1: ";

cin >>p1.x_coordinate >>p1.y_coordinate;

cout <<"Enter coordinates for p2: ";

cin >>p2.x_coordinate >>p2.y_coordinate;

p3.x_coordinate = p1.x_coordinate + p2.x_coordinate;

p3.y_coordinate = p1.y_coordinate + p2.y_coordinate;

cout <<"Coordinates of p1 + p2 are: " <<p3.x_coordinate <<", " <<p3.y_coordinate;

return 0;

Q 3. Create a structure called Volume that uses three variables of type Distance (from the ENGLSTRC
example) to model the volume of a room. Initialize a variable of type Volume to specific dimensions, then
calculate the volume it represents, and print out the result. To calculate the volume, convert each
dimension from a Distance variable to a variable of type float representing feet and fractions of a foot,
and then multiply the resulting three numbers.

Solution:

#include<iostream>
using namespace std;
struct Distance {

int feet;

float inches;

};

struct volume {

Distance length;
Distance width;
Distance height;
};

int main()

float l, w, h;

volume room = {{2, 6.3}, {4, 2.3}, {3, 8.3}};

cout <<"Length of the room is: " <<room.length.feet <<"\'-" <<room.length.inches <<"\""

<<endl;

cout <<"Width of the room is: " <<room.width.feet <<"\'-" <<room.width.inches <<"\"" <<endl

cout <<"Height of the room is: " <<room.height.feet <<"\'-" <<room.height.inches <<"\""
<<endl;

l = room.length.feet + room.length.inches/12.0;

w = room.width.feet + room.width.inches/12.0;

h = room.height.feet + room.height.inches/12.0;

float vol = l*w*h;

cout <<"\nVolume of the room is: " <<vol <<" cubic feet" <<endl;

return 0;

Q 4. Create a structure called employee that contains two members: an employee number (type int) and
the employee’s compensation (in dollars; type float). Ask the user to fill in this data for three employees,
store it in three variables of type struct employee, and then display the information for each employee.

Soution:

#include<iostream>
using namespace std;
struct employee

{
int emp_number;
float emp_compensation;
};

int main() {

employee emp1, emp2, emp3;

cout <<"Enter the details of employee 1 :-->" <<endl;

cout <<"\nEnter the employee number: ";

cin >>emp1.emp_number;

cout <<"Enter the employee compensation: $";

cin >>emp1.emp_compensation;

cout <<"\nEnter the details of employee 2 :-->" <<endl;

cout <<"Enter the employee number: ";

cin >>emp2.emp_number;

cout <<"Enter the employee compensation: $";

cin >>emp2.emp_compensation;

cout <<"\nEnte the details of employee 3 :-->" <<endl;

cout <<"Entewr the epmoyee number: ";

cin >>emp3.emp_number;

cout <<"Enter the epmoyee compensation: $";

cin >>emp3.emp_compensation;cout <<endl;


cout <<"\nEmployee Details:--> " <<endl;

cout <<"\nEmployee-1: employee number: " <<emp1.emp_number <<endl;

cout <<"Employee-1: employee compensation: $" <<emp1.emp_compensation <<endl;


cout <<"\nEmployee-2: employee number: " <<emp2.emp_number <<endl;
cout <<"Employee-2: employee compensation: $" <<emp2.emp_compensation <<endl;

cout <<"\nEmployee-3: employee number: " <<emp3.emp_number <<endl;


cout <<"Employee-3: employee compensation: $" <<emp3.emp_compensation <<endl;
return 0;
}

Q 5. Create a structure of type date that contains three members: the month, the day of the month, and
the year, all of type int. (Or use day-month-year order if you prefer.) Have the user enter a date in the
format 12/31/2001, store it in a variable of type struct date, then retrieve the values from the variable and
print them out in the same format.

Solution:

#include<iostream>
using namespace std;
struct dat {

int day;
int month;
int year;
};

int main() {

dat mdy;

cout <<"Enter the date in mm/dd/yy format:\n ";


cin >>mdy.month >>mdy.day >>mdy.year;
cout <<"User inputed date is: " <<mdy.month <<"/" <<mdy.day <<"/" <<mdy.year;
return 0;

Q 6. We said earlier that C++ I/O statements don’t automatically understand the data types of
enumerations. Instead, the (>>) and (<<)operators think of such variables simply as integers. You can
overcome this limitation by using switch statements to translate between the user’s way of expressing an
enumerated variable and the actual values of the enumerated variable. For example, imagine an
enumerated type with values that indicate an employee type within an organization:
enum etype { laborer, secretary, manager, accountant, executive, researcher };
Write a program that first allows the user to specify a type by entering its first letter (‘l’, ‘s’, ‘m’, and so
on), then stores the type chosen as a value of a variable of type enum etype, and finally displays the
complete word for this type. Enter employee type (first letter only) laborer, secretary, manager,
accountant, executive, researcher): a Employee type is accountant. You’ll probably need two switch
statements: one for input and one for output.

Solution:
#include<iostream>
using namespace std;
enum etype {laborer, secretary, manager, accountant, executive, researcher};
int main() {
etype emp;
char select_type;
cout <<"\nEnter employee type (first letter only: laborer, secretary, manager, accountant,
executive, researcher): ";
cin >>select_type;

switch(select_type)
{
case 'l': emp = laborer;
break;

case 's':emp = secretary;


break;

case 'm': emp = manager;


break;

case 'a': emp = accountant;


break;
case 'e': emp = executive;
break;

case 'r':emp = researcher;


break;
default: cout <<"Invalid Selection!\n";
}
switch(emp)
{
case laborer:
cout <<"Employee type is laborer\n";
break;

case secretary:
cout <<"Employee type is secretary\n";
break;

case manager:
cout <<"Employee type is manager\n";
break;
case accountant:
cout <<"Employee type is accountant\n";
break;
case executive:
cout <<"Employee type is executive\n";
break;

case researcher:
cout <<"Employee type is researcher\n";
break;
default:
cout <<"No match found!\n";
}

return 0;
}

Q 7. Add a variable of type enum etype (see Exercise 6), and another variable of type struct date (see
Exercise 5) to the employee class of Exercise 4. Organize the resulting program so that the user enters
four items of information for each of three employees: an employee number, the employee’s
compensation, the employee type, and the date of first employment. The program should store this
information in three variables of type employee, and then display their contents.

Solution:
#include<iostream>
using namespace std;
enum etype {laborer, secretary, manager, accountant, executive, researcher};
struct date {
int month;
int day;
int year;
};
struct employee {
int emp_num;
float emp_compen;
date mdy;
etype emp_type;
};
int main() {
employee emp1, emp2, emp3;
char e_type;
cout <<"\nEnter the first employee details: ";
cout <<"\nEnter employee number: ";
cin >>emp1.emp_num;
cout <<"Enter employee compensation: ";
cin >>emp1.emp_compen;
cout <<"Enter employee type: ";
cin >>e_type;

switch(e_type) {
case 'l':
emp1.emp_type = laborer;
break;

case 's':
emp1.emp_type = secretary;
break;

case 'm':
emp1.emp_type = manager;
break;

case 'a':
emp1.emp_type = accountant;
break;

case 'e':
emp1.emp_type = executive;
break;

case 'r':
emp1.emp_type = researcher;
break;

default:
cout <<"Invalid Input!";
}

cout <<"Enter date of first employment: ";


cin >>emp1.mdy.month >>emp1.mdy.day >>emp1.mdy.year;

cout <<"\nEnter the second employee details: ";


cout <<"\nEnter employee number: ";
cin >>emp2.emp_num;
cout <<"Enter employee compensation: ";
cin >>emp2.emp_compen;
cout <<"Enter employee type: ";
cin >>e_type;

switch(e_type) {
case 'l':
emp2.emp_type = laborer;
break;

case 's':
emp2.emp_type = secretary;
break;

case 'm':
emp2.emp_type = manager;
break;

case 'a':
emp2.emp_type = accountant;
break;

case 'e':
emp2.emp_type = executive;
break;

case 'r':
emp2.emp_type = researcher;
break;

default:
cout <<"Invalid Input!";
}
cout <<"Enter date of first employment: ";
cin >>emp2.mdy.month >>emp2.mdy.day >>emp2.mdy.year;

cout <<"\nEnter the third employee details: ";


cout <<"\nEnter employee number: ";
cin >>emp3.emp_num;
cout <<"Enter employee compensation: ";
cin >>emp3.emp_compen;
cout <<"Enter employee type: ";
cin >>e_type;

switch(e_type)
{
case 'l':
emp3.emp_type = laborer;
break;

case 's':
emp3.emp_type = secretary;
break;

case 'm':
emp3.emp_type = manager;
break;

case 'a':
emp3.emp_type = accountant;
break;

case 'e':
emp3.emp_type = executive;
break;

case 'r':
emp3.emp_type = researcher;
break;

default:
cout <<"Invalid Input!";
}
cout <<"Enter date of first employment: ";
cin >>emp3.mdy.month >>emp3.mdy.day >>emp3.mdy.year;

cout <<"\nDetails of first employee: ";


cout <<"\nEmployee number: " <<emp1.emp_num;
cout <<"\nEmployee compensation: " <<emp1.emp_compen;
cout <<"\nEmployee type is: ";
switch(emp1.emp_type) {
case laborer:
cout <<"Laborer";
break;

case secretary:
cout <<"Secretary";
break;

case manager:
cout <<"Manager";
break;

case accountant:
cout <<"Accountant";
break;

case executive:
cout <<"Executive";
break;

default:
cout <<"No match found!";
}

cout <<"\nEmployee date of first employment: " <<emp1.mdy.month <<"/" <<emp1.mdy.day


<<"/" <<emp1.mdy.year <<endl;

cout <<"\nDetails of second employee: ";


cout <<"\nEmployee number: " <<emp2.emp_num;
cout <<"\nEmployee compensation: " <<emp2.emp_compen;
cout <<"\nEmployee type is: ";
switch(emp2.emp_type) {
case laborer:
cout <<"Laborer";
break;

case secretary:
cout <<"Secretary";
break;
case manager:
cout <<"Manager";
break;

case accountant:
cout <<"Accountant";
break;

case executive:
cout <<"Executive";
break;

default:
cout <<"No match found!";
}
cout <<"Employee date of first employment: " <<emp2.mdy.month <<"/"
<<emp2.mdy.day <<"/" <<emp2.mdy.year <<endl;

cout <<"\nDetails of first employee: ";


cout <<"\nEmployee number: " <<emp3.emp_num;
cout <<"\nEmployee compensation: " <<emp3.emp_compen;
cout <<"\nEmployee type is: ";
switch(emp3.emp_type) {
case laborer:
cout <<"Laborer";
break;

case secretary:
cout <<"Secretary";
break;

case manager:
cout <<"Manager";
break;

case accountant:
cout <<"Accountant";
break;

case executive:
cout <<"Executive";
break;

default:
cout <<"No match found!";
}
cout <<"\nEmployee date of first employment: " <<emp3.mdy.month <<"/"
<<emp3.mdy.day <<"/" <<emp3.mdy.year <<endl;
return 0;
}

Problem 8. Start with the fraction-adding program of Exercise 9 in Chapter 2, “C++ Programming
Basics.” This program stores the numerator and denominator of two fractions before adding them, and
may also store the answer, which is also a fraction. Modify the program so that all fractions are stored in
variables of type struct fraction, whose two members are the fraction’s numerator and denominator (both
type int). All fractionrelated data should be stored in structures of this type.

#include<iostream>
using namespace std;
struct fraction {
int numerator;
int denominator;
char dummychar;
};
int main()
{
fraction f1, f2, f3;
cout <<"Enter first fraction: ";
cin >>f1.numerator >>f1.dummychar >>f1.denominator;

cout <<"Enter second fraction: ";


cin >>f2.numerator >>f2.dummychar >>f2.denominator;

f3.numerator = f1.numerator*f2.denominator + f1.denominator*f2.numerator;


f3.denominator = f1.denominator*f2.denominator;

cout <<"Addition of two fraction is: " <<f3.numerator <<"/" <<f3.denominator <<endl;
return 0;
}

Q 9. Create a structure called time. Its three members, all type int, should be called hours, minutes, and
seconds. Write a program that prompts the user to enter a time value in hours, minutes, and seconds. This
can be in 12:59:59 format, or each number can be entered at a separate prompt (“Enter hours:”, and so
forth). The program should then store the time in a variable of type struct time, and finally print out the
total number of seconds represented by this time value: long totalsecs = t1.hours*3600 + t1.minutes*60 +
t1.seconds.

Solution:
#include<iostream>
using namespace std;
struct time {
int hours;
int minutes;
int seconds;
char dummycolon;
};
int main()
{
time t1;
cout <<"Enter the time value (i.e hours, minutes, seconds): ";
cin >>t1.hours >>t1.dummycolon >>t1.minutes >>t1.dummycolon >>t1.seconds;

long totalsecs = t1.hours*3600 + t1.minutes*60 + t1.seconds;


cout <<"Total number of seconds are: " <<totalsecs <<endl;
return 0;
}

Q 10. Create a structure called sterling that stores money amounts in the old-style British system
discussed in Exercises 8 and 11 in Chapter 3, “Loops and Decisions.” The members could be called
pounds, shillings, and pence, all of type int. The program should ask the user to enter a money amount in
new-style decimal pounds (type double), convert it to the old-style system, store it in a variable of type
struct sterling, and then display this amount in pounds-shillings-pence format.

Solution:
#include<iostream>
using namespace std;
struct sterling {
int pounds;
int shilling;
int pence;
};
int main()
{
sterling money;
double dec_pound, decfrac, decpence, dec_pence;
int user_pound, user_pence;
cout <<"Enter the decimal pound: ";
cin >>dec_pound;

user_pound = static_cast<int>(dec_pound);
decfrac = dec_pound - user_pound;
dec_pence = decfrac*20;
user_pence = static_cast<int>(dec_pence);
decpence = dec_pence - user_pence;

money.pounds = user_pound;
money.shilling = dec_pence;
money.pence = decpence*12;

cout <<"Amount in old style system i.e (pounds-shilling-pence format): ";


cout <<"\x9C" <<money.pounds <<"." <<money.shilling <<"." <<money.pence <<endl;
return 0;
}

Q 11. Use the time structure from Exercise 9, and write a program that obtains two time values from the
user in 12:59:59 format, stores them in struct time variables, converts each one to seconds (type int), adds
these quantities, converts the result back to hoursminutes-seconds, stores the result in a time structure,
and finally displays the result in 12:59:59 format.

Solution:
#include<iostream>
using namespace std;

struct time {
int hours;
int minutes;
int seconds;
char dumychar;
};
int main() {
time t1, t2, t3;
float total_time, temp_hours, frac_hours, temp_minutes, frac_minutes;
cout <<"Enter the first time value in hh:mm:ss format: ";
cin >>t1.hours >>t1.dumychar >>t1.minutes >>t1.dumychar >>t1.seconds;

cout <<"Enter the second time value in hh:mm:ss format: ";


cin >>t2.hours >>t2.dumychar >>t2.minutes >>t2.dumychar >>t2.seconds;

t1.hours *= 3600; t1.minutes *= 60;


t2.hours *= 3600; t2.minutes *= 60;

total_time = t1.hours + t1.minutes + t1.seconds + t2.hours + t2.minutes +t2.seconds;

temp_hours = total_time/3600;
t3.hours = temp_hours;
frac_hours = temp_hours - t3.hours;
temp_minutes = frac_hours*60;
t3.minutes = temp_minutes;
frac_minutes = temp_minutes - t3.minutes;
cout <<frac_minutes <<endl;

t3.seconds = frac_minutes*60;

cout <<"\nTotal time in hh:mm:ss format is: " <<t3.hours <<":" <<t3.minutes <<":" <<t3.seconds
<<endl;
return 0;
}

Q12. Revise the four-function fraction calculator program of Exercise 12 in Chapter 3 so that each
fraction is stored internally as a variable of type struct fraction, as discussed in Exercise 8 in this chapter.

Solution:
#include<iostream>
using namespace std;
struct fraction {
int numerator;
int denominator;
char dummychar;
};
int main() {
fraction frac1, frac2, frac3;
char opr;
cout <<"Enter first fraction: ";
cin >>frac1.numerator >>frac1.dummychar >>frac1.denominator;

cout <<"Enter second fraction: ";


cin >>frac2.numerator >>frac2.dummychar >>frac2.denominator;
cout <<"Enter slect an operator(+,-,*,/) for performing suitable operations: ";
cin >>opr;

switch(opr) {
case '+':
frac3.numerator = frac1.numerator*frac2.denominator +
frac1.denominator*frac2.numerator;
frac3.denominator = frac1.denominator*frac2.denominator;
cout <<frac3.numerator <<"/" <<frac3.denominator;
break;

case '-':
frac3.numerator = frac1.numerator*frac2.denominator -
frac1.denominator*frac2.numerator;
frac3.denominator = frac1.denominator*frac2.denominator;
cout <<frac3.numerator <<"/" <<frac3.denominator;
break;

case '*':
frac3.numerator = frac1.numerator*frac2.numerator;
frac3.denominator = frac1.denominator*frac2.denominator;
cout <<frac3.numerator <<"/" <<frac3.denominator;
break;
case '/':
frac3.numerator = frac1.numerator*frac2.denominator;
frac3.denominator = frac1.denominator*frac2.numerator;
cout <<frac3.numerator <<"/" <<frac3.denominator;
break;
default:
cout <<"Invalid Selection!";
}
return 0;
}

CHAPTER# 5

Q1. Refer to the CIRCAREA program in Chapter 2, “C++ Programming Basics.” Write a function called
circarea() that finds the area of a circle in a similar way. It should take an argument of type float and
return an argument of the same type. Write a main() function that gets a radius value from the user, calls
circarea(), and displays the result.

Solution:

#include<iostream>
using namespace std;

float circarea(float);

int main() {
float rad;
cout <<"\nEnter radius of a circle: ";
cin >>rad;
cout <<"Area of circle is: " <<circarea(rad) <<endl;
return 0;
}
float circarea(float rads)
{
return 3.14159*rads*rads;
}

Q2. Raising a number n to a power p is the same as multiplying n by itself p times. Write a function
called power() that takes a double value for n and an int value for p, and returns the result as a double
value. Use a default argument of 2 for p, so that if this argument is omitted, the number n will be squared.
Write a main() function that gets values from the user to test this function.

Solution:
#include<iostream>
using namespace std;

double power(double, int=2);


int main() {
double num, answer;
int pow;
char ch;
cout <<"\nEnter a number: ";
cin >>num;
cout <<"Want to enter the power Y/N: ";
cin >>ch;
if(ch == 'y' || ch == 'Y') {
cout <<"Enter the power: ";
cin >>pow;
answer = power(num, pow);
} else {
answer = power(num);
}
cout <<"The value of power is: " <<answer <<endl;
return 0;
}
double power(double n, int power)
{
double ans = 1.0;
for(int i=1; i<=power; i++)
{
ans *= n;
}
return ans;
}
Output:
Q3. Write a function called zeroSmaller() that is passed two int arguments by reference and then sets the
smaller of the two numbers to 0. Write a main() program to exercise this function.

Solution:
#include<iostream>
using namespace std;
void zeroSmaller(int&, int&);

int main() {
int num1, num2;
cout <<"\nEnter two integer number: ";
cin >> num1 >>num2;
zeroSmaller(num1, num2);
cout <<"Number 1 is: " <<num1 <<endl;
cout <<"Number 2 is: " <<num2 <<endl;
return 0;
}
void zeroSmaller(int& a, int& b) {
if(a>b)
b=0;
else
a=0;
}

Q4. Write a function that takes two Distance values as arguments and returns the larger one. Include a
main() program that accepts two Distance values from the user, compares them, and displays the larger.
(See the RETSTRC program for hints.)

Solution:
#include<iostream>
using namespace std;

struct Distance {
int feet;
float inches;
};

Distance lrgDist(Distance, Distance);


void lrgdisp(Distance);
int main() {
Distance d1, d2, d3;
cout <<"\nEnter first distance in feet: ";
cin >>d1.feet;
cout <<"Enter first distance in inches: ";
cin >>d1.inches;
cout <<"\nEnter second distance in feet: ";
cin >>d2.feet;
cout <<"Enter second distance in inches: ";
cin >>d2.inches;

d3 = lrgDist(d1, d2);

cout <<"\nd1: "; lrgdisp(d1);


cout <<"d2: "; lrgdisp(d2);

cout <<"\nThe largest distance is: ";


lrgdisp(d3);
return 0;
}
Distance lrgDist(Distance dd1, Distance dd2)
{
if(dd1.feet > dd2.feet)
{
return dd1;

}
else if(dd2.feet > dd1.feet) {
return dd2;

} else if(dd1.inches > dd2.inches) {


return dd1;

} else {
return dd2;
}
}

void lrgdisp(Distance disp) {


cout <<disp.feet <<"' -" <<disp.inches <<"\"" <<endl;
}

Q 5. Write a function called hms_to_secs() that takes three int values—for hours, minutes, and seconds
—as arguments, and returns the equivalent time in seconds (type long). Create a program that exercises
this function by repeatedly obtaining a time value in hours, minutes, and seconds from the user (format
12:59:59), calling the function, and displaying the value of seconds it returns.

Solution:
#include<iostream>
using namespace std;

long hms_to_secs(int, int, int);

int main()
{
int hours, minutes, seconds;
char ch = 'a';
do {
cout <<"\nEnter hours: ";
cin >>hours;
cout <<"Enter minutes: ";
cin >>minutes;
cout <<"Enter seconds: ";
cin >>seconds;
cout <<"\nPress s to submit your values: ";
cin >>ch;
}
while(ch !='s');

cout <<"\nTotal time in seconds is: " <<hms_to_secs(hours, minutes, seconds) <<endl;
return 0;
}
long hms_to_secs(int hh, int mm, int ss)
{
long total_seconds = hh*3600 + mm*60 + ss;
return total_seconds;
}

Q 6. Start with the program from Exercise 11 in Chapter 4, “Structures,” which adds two struct time
values. Keep the same functionality, but modify the program so that it uses two functions. The first,
time_to_secs(), takes as its only argument a structure of type Chapter 5 212 06 3087 CH05 11/29/01 2:23
PM Page 212 time, and returns the equivalent in seconds (type long). The second function,
secs_to_time(), takes as its only argument a time in seconds (type long), and returns a structure of type
time.

Solution:
#include<iostream>
using namespace std;

struct time {
int hours;
int minutes;
int seconds;
};
long time_to_secs(time);
time secs_to_time(long);
void disp_time(time);
int main()
{
time t1, str_time;
long time;
cout <<"\nEnter hours: ";
cin >>t1.hours;
cout <<"Enter minutes: ";
cin >>t1.minutes;
cout <<"Enter seconds: ";
cin >>t1.seconds;
cout <<"Total time structure in seconds is: " <<time_to_secs(t1);
cout <<"\n\nEnter total time in seconds: ";
cin >>time;
str_time = secs_to_time(time);
cout <<"Total seconds in time structure is: "; disp_time(str_time);

return 0;
}
long time_to_secs(time tt1)
{
return tt1.hours*3600 + tt1.minutes*60 + tt1.seconds;
}
time secs_to_time(long tt2)
{
int hh, mm, ss;
time tme;
mm = tt2/60;
ss = tt2%60;
hh = mm/60;
mm = mm%60;

tme.hours = hh;
tme.minutes = mm;
tme.seconds = ss;

return tme;
}
void disp_time(time tms)
{
cout <<tms.hours <<":" <<tms.minutes <<":" <<tms.seconds <<endl;
}

Q 7. Start with the power() function of Exercise 2, which works only with type double. Create a series of
overloaded functions with the same name that, in addition to double, also work with types char, int, long,
and float. Write a main() program that exercises these overloaded functions with all argument types.

Solution:
#include<iostream>
using namespace std;
double power(double, int=2);
char power(char, int=2);
int power(int, int=2);
long power(long, int=2);
float power(float, int=2);

int main()
{
double num1;
char num2;
int num3;
long num4;
float num5;

cout <<"\nEnter a double vale for power calculation: ";


cin >>num1;
cout <<"Power of " <<num1 <<" is: " <<power(num1);

cout <<"\n\nnEnter a char value for power calculation: ";


cin >>num2;
cout <<"Power of " <<num2 <<" is: " <<power(num2);

cout <<"\n\nEnter a int value for power calculation: ";


cin >>num3;
cout <<"Power of " <<num3 <<" is: " <<power(num3);

cout <<"\n\nEnter a long value for power calculation: ";


cin >>num4;
cout <<"Power of " <<num4 <<" is: " <<power(num4);
cout <<"\n\nEnter a float value for power calculation: ";
cin >>num5;
cout <<"Power of " <<num5 <<" is: " <<power(num5);

cout <<endl;

return 0;
}

//power(double)
double power(double dd, int p) {
double power = 1;
for(int i=1; i<=p; i++)
power *= dd;
return power;
}

char power(char ch, int p) {


char power = 1;
for(int i=1; i<=p; i++)
power *= ch;
return power;
}

int power(int no1, int p)


{
int power = 1;
for(int i=1; i<=p; i++)
power *= no1;
return power;
}

long power(long numb, int p) {


long power = 1;
for (int i=1; i<=p; i++)
power *= numb;
return power;
}
float power(float number, int p) {
float power = 1.0;
for (int i=1; i<=p; i++)
power *= number;
return power;
}

Q 8. Write a function called swap() that interchanges two int values passed to it by the calling program.
(Note that this function swaps the values of the variables in the calling program, not those in the
function.) You’ll need to decide how to pass the arguments. Create a main() program to exercise the
function.

Solution:
#include<iostream>
using namespace std;
void swap(int&, int&);

int main()
{
int num1, num2;
cout <<"\nEnter two number for swaping: ";
cin >>num1 >>num2;
cout <<"\nnum1 is: " <<num1 <<endl;
cout <<"num2 is: " <<num2 <<endl;
swap(num1, num2);
cout <<"\n\nAfter swap num1 is " <<num1 <<endl;
cout <<"After swap num2 is " <<num2 <<endl;
return 0;
}
void swap(int& a, int& b)
{
int temp = a;
a=b;
b=temp;
}

Q 9. Repeat Exercise 8, but instead of two int variables, have the swap() function interchange two struct
time values (see Exercise 6).

Solution:
#include<iostream>
using namespace std;

struct time {
int hours;
int minutes;
int seconds;
};
void swapTime(time&, time&);
void swapTimeDisp(time);
int main()
{
time t1, t2;
cout <<"\nEnter 1st time hours: "; cin >>t1.hours;
cout <<"Enter 1st time minutes: "; cin >>t1.minutes;
cout <<"Enter 1st time seconds: "; cin >>t1.seconds;

cout <<"\n\nEnter 2nd time hours: "; cin >>t2.hours;


cout <<"Enter 2nd time minutes: "; cin >>t2.minutes;
cout <<"Enter 2nd time seconds: "; cin >>t2.seconds;

cout <<"\n\nBefore swap 1st time is: "; swapTimeDisp(t1);


cout <<"Before swap 2st time is: "; swapTimeDisp(t2);

swapTime(t1, t2);

cout <<"\n\nAfter swap 1st time is: "; swapTimeDisp(t1);


cout <<"After swap 2nd time is: "; swapTimeDisp(t2);

return 0;
}
void swapTime(time& tm1, time& tm2)
{
time temp;
temp.hours = tm1.hours;
temp.minutes = tm1.minutes;
temp.seconds = tm1.seconds;

tm1.hours = tm2.hours;
tm1.minutes = tm2.minutes;
tm1.seconds = tm2.seconds;

tm2.hours = temp.hours;
tm2.minutes = temp.minutes;
tm2.seconds = temp.seconds;
}
void swapTimeDisp(time tme)
{
cout <<tme.hours <<":" <<tme.minutes <<":" <<tme.seconds <<endl;
}

Q10. Write a function that, when you call it, displays a message telling how many times it has been
called: “I have been called 3 times”, for instance. Write a main() program that calls this function at least
10 times. Try implementing this function in two different ways. First, use a global variable to store the
count. Second, use a local static variable. Which is more appropriate? Why can’t you use a local variable?

Solution:
#include<iostream>
using namespace std;

int count=0;

void globalVar();

int localstatic();

int main() {
int store;
globalVar();
globalVar();
globalVar();
globalVar();
globalVar();
globalVar();
globalVar();
globalVar();
globalVar();
globalVar();
localstatic();
localstatic();
localstatic();
localstatic();
localstatic();
localstatic();
store = localstatic();

cout <<"\nI have been called " <<count <<" times using global variable" <<endl;
cout <<"\nI have been called " <<store <<" times using local static variable" <<endl;
return 0;
}
void globalVar()
{
count++;
}
int localstatic()
{
static int remember = 0;
remember++;
return remember;
}

Q 11. Write a program, based on the sterling structure of Exercise 10 in Chapter 4, that obtains from the
user two money amounts in old-style British format (£9:19:11), adds them, and displays the result, again
in old-style format. Use three functions. The first should obtain a pounds-shillings-pence value from the
user and return the value as a structure of type sterling. The second should take two arguments of type
sterling and return a value of the same type, which is the sum of the arguments. The third should take a
sterling structure as its argument and display its value.

Solution:
#include<iostream>
using namespace std;
struct sterling
{
int pound;
int shilling;
int pence;
};
sterling BritishCurrency(int, int, int);
sterling sterlingfunc(sterling, sterling);
void sterlingDisp(sterling);
int main()
{
int pound, shilling, pence;
sterling firstValue, secondValue;
sterling s1 = {2, 10, 5};
sterling s2 = {9,18, 10};
cout <<"\nEnter pound: "; cin >>pound;
cout <<"Enter shilling: "; cin >>shilling;
cout <<"Enter pence: "; cin >>pence;
firstValue = BritishCurrency(pound, shilling, pence);
secondValue = sterlingfunc(s1, s2);
cout <<"\nFirst value is: "; sterlingDisp(firstValue);
cout <<"\nSecond value is: "; sterlingDisp(secondValue);
cout <<endl;
return 0;
}
sterling BritishCurrency(int pnd, int shl, int pen) {
sterling currency;
currency.pound = pnd;
currency.shilling = shl;
currency.pence = pen;
return currency;
}
sterling sterlingfunc(sterling ss1, sterling ss2)
{
sterling result;
result.pound = ss1.pound + ss2.pound;
result.shilling = ss1.shilling + ss2.shilling;
result.pence = ss1.pence + ss2.pence;

if(result.pence > 11) {


result.shilling++;
result.pence = 0;
}
if(result.shilling > 19)
{
reuslt.pound++;
}
return result;
}
void sterlingDisp(sterling valueDisp) {
cout <<"\x9c" <<valueDisp.pound <<":" <<valueDisp.shilling <<":" <<valueDisp.pence;
}

Q 12. Revise the four-function fraction calculator from Exercise 12, Chapter 4, so that it uses functions
for each of the four arithmetic operations. They can be called fadd(), fsub(), fmul(), and fdiv(). Each of
these functions should take two arguments of type struct fraction, and return an argument of the same
type.

Solution:
#include<iostream>
using namespace std;
struct strctValue
{
int numerator;
int denominator;
char dummyslash;
};
strctValue fadd(strctValue, strctValue);
strctValue fsub(strctValue, strctValue);
strctValue fmul(strctValue, strctValue);
strctValue fdiv(strctValue, strctValue);
void strctDisp(strctValue);
int main()
{
strctValue value1, value2, addshow, subshow, mulshow, divshow;
char option;
cout <<"\nEnter value for first fraction in (a/b) format: ";
cin >>value1.numerator >>value1.dummyslash >>value1.denominator;
cout <<"Enter value for second fraction in (c/d) format: ";
cin >>value2.numerator >>value2.dummyslash >> value2.denominator;

cout <<"\nChoose an operator for performing respective operation (+, -, *, /): ";
cin >>option;
switch(option)
{
case '+':
addshow = fadd(value1, value2);
cout <<"\nValue of addition is: "; strctDisp(addshow);
break;
case '-':
subshow = fsub(value1, value2);
cout <<"\nValue of subtraction is: "; strctDisp(subshow);
break;
case '*':
mulshow = fmul(value1, value2);
cout <<"\nValue of multiplication is: "; strctDisp(mulshow);
break;

case '/':
divshow = fdiv(value1, value2);
cout <<"\nValue of division is: "; strctDisp(divshow);
break;
default:
cout <<"Invalid operator";
}
cout <<endl;
return 0;
}
strctValue fadd(strctValue val1, strctValue val2) {
strctValue add;
add.numerator = val1.numerator*val2.denominator + val1.denominator*val2.numerator;
add.denominator = val2.denominator*val2.denominator;
return add;
}
strctValue fsub(strctValue val1, strctValue val2) {
strctValue sub;
sub.numerator = val1.numerator*val2.denominator - val1.denominator*val2.numerator;
sub.denominator = val1.denominator*val2.denominator;
return sub;
}
strctValue fmul(strctValue val1, strctValue val2) {
strctValue mul;
mul.numerator = val1.numerator*val2.numerator;
mul.denominator = val1.denominator*val2.denominator;
return mul;
}
strctValue fdiv(strctValue val1, strctValue val2) {
strctValue div;
div.numerator = val1.numerator*val2.denominator;
div.denominator = val1.denominator*val2.numerator;
return div;
}
void strctDisp(strctValue disp)
{
cout <<disp.numerator <<"/" <<disp.denominator;
}

You might also like