Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

C++ solutions for : [Object-Oriented Programming in C++, Third Edition]

بسم الله الرحمن الرحيم

PLEASE DON'T REPLY IN THIS THREAD , any discusions put them in a new thread with a quote of my post .

I'll put here C++ solutions for:
Object-Oriented Programming in C++, Third Edition
By Robert Lafore, Waite Group .

<<<<<<<<<<<<<<<<<<<<<
Solutions made By Amahdy.
>>>>>>>>>>>>>>>>>>>>>
[602 byte] By [Amahdy] at [2007-11-11 10:05:16]
# 1 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
CHAPTER 1THE BIG PICTURE

Questions:
----
1. Pascal, BASIC, and C are p___ languages, while C++ is an o ____.language.
2. A widget is to the blueprint for a widget as an object is to
a. a member function.
b. a class.
c. an operator.
d. a data item.
3. The two major components of an object are ___ and functions that _____.
4. In C++, a function contained within a class is called
a. a member function.
b. an operator.
c. a class function.
d. a method.
5. Protecting data from access by unauthorized functions is called ____.
6. Which of the following are good reasons to use an object-oriented language?
a. You can define your own data types.
b. Program statements are simpler than in procedural languages.
c. An OO program can be taught to correct its own errors.
d. Its easier to conceptualize an OO program.
7. _____ model entities in the real world more closely than do functions.
8. True or false: A C++ program is similar to a C program except for the details of coding.
9. Bundling data and functions together is called ____.
10. When a language has the capability to produce new data types, it is said to be
a. reprehensible.
b. encapsulated.
c. overloaded.
d. extensible.
11. True or false: You can easily tell, from any two lines of code, whether a program is written in C or C++.
12. The ability of a function or operator to act in different ways on different data types is called __________.
13. A normal C++ operator that acts in special ways on newly defined data types is said to be
a. glorified.
b. encapsulated.
c. classified.
d. overloaded.
14. Memorizing the new terms used in C++ is
a. critically important.
b. something you can return to later.
c. the key to wealth and success.
d. completely irrelevant.
__________

My answers:
----
1. procedural, object oriented.
2. a class.
3. ?, ?.
4. a member function.
5. block access.
6. You can define your own data types, An OO program can be taught to correct its own errors.
7. Class.
8. False.
9. ?.
10. reprehensible.
11. False.
12. ?.
13. classified.
14. something you can return to later.
___________

Answers:
---
1. procedural, object-oriented
2. b
3. data, act on that data
4. a
5. data hiding
6. a, d
7. objects
8. False; the organizational principles are different.
9. encapsulation
10. d
11. False; most lines of code are the same in C and C++.
12. polymorphism
13. d
14. b
________
Amahdy at 2007-11-11 20:59:23 >
# 2 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
CHAPTER 2C++ PROGRAMMING BASICS

Questions:
----
1. Dividing a program into functions
a. is the key to Object-Oriented Programming.
b. makes the program easier to conceptualize.
c. may reduce the size of the program.
d. makes the program run faster.
2. A function name must be followed by ________.
3. A function body is delimited by ________.
4. Why is the main() function special?
5. A C++ instruction that tells the computer to do something is called a ________.
6. Write an example of a normal C++ comment and an example of an old-fashioned /* comment.
7. An expression
a. usually evaluates to a numerical value.
b. indicates the emotional state of the program.
c. always occurs outside a function.
d. may be part of a statement.
8. Specify how many bytes are occupied by the following data types in a 32-bit system:
a. Type int
b. Type long double
c. Type float
d. Type long
9. True or false: A variable of type char can hold the value 301.
10. What kind of program elements are the following?
a. 12
b. a
c. 4.28915
d. JungleJim
e. JungleJim()
11. Write statements that display on the screen
a. the character x.
b. the name Jim.
c. the number 509.
12. True or false: In an assignment statement, the value on the left of the equal sign is always equal to the value on the right.
13. Write a statement that displays the variable george in a field 10 characters wide.
14. What header file must you #include with your source file to use cout and cin?
15. Write a statement that gets a numerical value from the keyboard and places it in the variable temp.
16. What header file must you perform #include with your program to use setw?
17. Two exceptions to the rule that the compiler ignores whitespace are ________ and ________.
18. True or false: Its perfectly all right to use variables of different data types in the same arithmetic expression.
19. The expression 11%3 evaluates to ________.
20. An arithmetic assignment operator combines the effect of what two operators?
21. Write a statement that uses an arithmetic assignment operator to increase the value of the variable temp by 23. Write the same statement without the arithmetic assignment operator.
22. The increment operator increases the value of a variable by how much?
23. Assuming var1 starts with the value 20, what will the following code fragment print out?
cout << var1--;
cout << ++var1;
24. In the examples weve seen so far, header files have been used for what purpose?
25. The actual code for library functions is contained in a ________ file.
__________

My answers:
----
1. makes the program easier to conceptualize, makes the program run faster.
2. '()'.
3. '{' and '}'.
4. The programme start from it.
5. an order, an event.
6. //Normal C++ comment, /*old-fashioned comment*/.
7. may be part of a statement.
8. Type int, Type long.
9. False.
10. 12 --> int,
'a' --> char,
4.28915 --> float,
JungleJim --> variable name,
JungleJim() --> function name.
11. #cout<<"x"; //or cout<<'x';
#cout<<"Jim";
#cout<<509;
12. False;
13. cout<<setw(10)<<george;
14. iostream.
15. cin >>temp;
16. iomanip.
17. between statments, end lines.
18. True.
19. 2.
20. assign, operation.
21. temp += 23;
temp = temp + 23;
22. 1
23. 20
21
24. to be able to use cout function.
25. lib.
___________

Answers:
---
1. b, c
2. parentheses
3. braces { }
4. Its the first function executed when the program starts
5. statement
6.
// this is a comment
/* this is a comment */

7. a, d
8. a. 4
b. 10
c. 4
d. 4
9. False
10. a. integer constant
b. character constant
c. floating-point constant
d. variable name or identifier
e. function name
11. a. cout << x;
b. cout << Jim;
c. cout << 509;
12. False; theyre not equal until the statement is executed.
13. cout << setw(10) << george;
14. IOSTREAM
15. cin >> temp;
16. IOMANIP
17. string constants, preprocessor directives
18. true
19. 2
20. assignment (=) and arithmetic (like + and *)
21.
temp += 23;
temp = temp + 23;

22. 1
23. 2020
24. to provide declarations and other data for library functions, overloaded operators, and objects
25. library
________
Amahdy at 2007-11-11 21:00:35 >
# 3 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
CHAPTER 2C++ PROGRAMMING BASICS codes;

/**1. Assuming there are 7.481 gallons in a cubic foot, write a program that asks the user to enter a
number of gallons, and then displays the equivalent in cubic feet.*/
#include<iostream.h>
#include<conio.h>

#define g_per_f 7.481

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n\n";

float n_gallons;

do{
cout<<"Enter the number of gallons : \xdb\t";
cin >>n_gallons;
cout<<"The equivalent in cubic feet : \xdb\t"<<n_gallons / g_per_f<<endl;
cout<<"\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/**2. Write a program that generates the following table:
1990 135
1991 7290
1992 11300
1993 16200

Use a single cout statement for all output.*/
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n\n";

int i, i_arr[4]={135,7290,11300,16200};

do{
for(i=1990;i<1994;i++) cout<<i<<setw(7)<<i_arr[i-1990]<<endl;
cout<<"\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/**3. Write a program that generates the following output:
10
20
19

Use an integer constant for the 10, an arithmetic assignment operator to generate the 20, and a
decrement operator to generate the 19. */
#include<iostream.h>
#include<conio.h>

#define ten 10

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n\n";

//int ten = 10; //### use this line in the place of "define"
//int second, third;
//second = 2*ten; third = second-1;
//cout<<ten<<endl<<second<<endl<<third<<endl;
do{
cout<<ten<<endl<<2*ten<<endl<<2*ten-1<<endl;
cout<<"\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*4. Write a program that displays your favorite poem. Use an appropriate escape sequence for the
line breaks. If you dont have a favorite poem, you can borrow this one by Ogden Nash:

Candy is dandy,
But liquor is quicker.
*/
#include<iostream.h>
#include<conio.h>

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n\n";

do{
cout<<"\tLa Ilah Ila Allah\n\tMohamed Rasoul Allah"<<endl;
cout<<"\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*5. A library function, islower(), takes a single character (a letter) as an argument and returns a
nonzero integer if the letter is lowercase, or zero if it is uppercase. This function requires the header
file CTYPE.H. Write a program that allows the user to enter a letter, and then displays either zero or
nonzero, depending on whether a lowercase or uppercase letter was entered. (See the SQRT
program for clues.)*/
#include<iostream.h>
#include<conio.h>
#include<ctype.h>

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n\n";

do{
cout<<"Enter a letter : \xdb\t"<<endl;
cout<<islower(getch())<<"\nthis value must be zero if you entred an uppercase letter and nonzero case else."<<endl;
cout<<"\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*6. On a certain day the British pound was equivalent to $1.487 U.S., the French franc was $0.172,
the German deutschemark was $0.584, and the Japanese yen was $0.00955. Write a program that
allows the user to enter an amount in dollars, and then displays this value converted to these four
other monetary units.*/
#include<iostream.h>
#include<conio.h>

#define pound 1.487
#define franc 0.172
#define deutschemark 0.584
#define yen 0.00955

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n\n";
int dollars;

do{
cout<<"Enter the U.S. amout : \xdb\t";
cin >>dollars;
cout<<endl;
cout<<"British pound =\t" << dollars / pound <<endl;
cout<<"French franc =\t" << dollars / franc <<endl;
cout<<"German deutschemark =\t" << dollars / deutschemark <<endl;
cout<<"Japanese yen =\t" << dollars / yen <<endl;
//cout<<"\nAnother operation ? (y/n) : "; //use this line to continue using the programme.
cout<<"\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}
Amahdy at 2007-11-11 21:01:26 >
# 4 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
/*7. You can convert temperature from degrees Celsius to degrees Fahrenheit by multiplying by 9/5
and adding 32. Write a program that allows the user to enter a floating-point number representing
degrees Celsius, and then displays the corresponding degrees Fahrenheit.*/
#include<iostream.h>
#include<conio.h>

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n\n";
float c_temp;

do{
cout<<"Enter the degrees Celsius\t\t\t\xdb ";
cin >>c_temp;
cout<<"The corresponding degrees Fahrenheit is :\t\xdb "<<((9/5)*c_temp)+32<<endl;
cout<<"\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*8. When a value is smaller than a field specified with setw(), the unused locations are, by default,
filled in with spaces. The manipulator setfill() takes a single character as an argument and causes this
character to be substituted for spaces in the empty parts of a field. Rewrite the WIDTH program so
that the characters on each line between the location name and the population number are filled in
with periods instead of spaces, as in

Portcity....2425785
*/
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
//WIDTH program:
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!// width2.cpp
!// demonstrates setw manipulator
!#include <iostream>
!#include <iomanip> // for setw
!using namespace std;
!
!int main()
! {
! long pop1=2425785, pop2=47, pop3=9761;
!
! cout << setw(8) << "LOCATION" << setw(12)
! << "POPULATION" << endl
! << setw(8) << "Portcity" << setw(12) << pop1 << endl
! << setw(8) << "Hightown" << setw(12) << pop2 << endl
! << setw(8) << "Lowville" << setw(12) << pop3 << endl;
! return 0;
! }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n\n";
long pop1=2425785, pop2=47, pop3=9761;

do{
cout << setw(8) << "LOCATION" << setw(12)
<< "POPULATION" << endl
<< setw(8) << "Portcity" << setw(12) << setfill('.') << pop1 << endl
<< setw(8) << "Hightown" << setw(12) << setfill('.') << pop2 << endl
<< setw(8) << "Lowville" << setw(12) << setfill('.') << pop3 << endl;
cout<<"\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*9. If you have two fractions, a/b and c/d, their sum can be obtained from the formula

a c a*d + b*c
-- + -- = ----
b d b*d

For example, 1/4 plus 2/3 is
1 2 1*3 + 4*2 3 + 8 11
-- + -- = ---- = --- = --
4 3 4*3 12 12

Write a program that encourages the user to enter two fractions, and then displays their sum in
fractional form. (You dont need to reduce it to lowest terms.) The interaction with the user might
look like this:

Enter first fraction: 1/2
Enter second fraction: 2/5
Sum = 9/10

You can take advantage of the fact that the extraction operator (>>) can be chained to read in more
than one quantity at once:

cin >> a >> dummychar >> b;
*/
#include<iostream.h>
#include<conio.h>

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n\n";
int first[2], last[2];
char operation; //In this sample programme not needed but generally for error detection only!

do{
cout<<"Enter first fraction: ";
cin >>first[0]>>operation>>last[0]; //if (operation != '/') {raise error event}
cout<<"Enter second fraction: ";
cin >>first[1]>>operation>>last[1]; //if (operation != '/') {raise error event}
cout<<"Sum = "<<(first[0]*last[1] + last[0]*first[1])<<operation<<(last[0]*last[1])<<endl;
cout<<"\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}
Amahdy at 2007-11-11 21:02:28 >
# 5 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
/*10. In the heyday of the British empire, Great Britain used a monetary system based on pounds,
shillings, and pence. There were 20 shillings to a pound, and 12 pence to a shilling. The notation for
this old system used the pound sign, , and two decimal points, so that, for example, 5.2.8 meant
5 pounds, 2 shillings, and 8 pence. (Pence is the plural of penny.) The new monetary system,
introduced in the 1950s, consists of only pounds and pence, with 100 pence to a pound (like U.S.
dollars and cents). Well call this new system decimal pounds. Thus 5.2.8 in the old notation is
5.13 in decimal pounds (actually 5.1333333). Write a program to convert the old pounds-
shillings-pence format to decimal pounds. An example of the users interaction with the program
would be

Enter pounds: 7
Enter shillings: 17
Enter pence: 9
Decimal pounds = 7.89

In both Borland C++ and Turbo C++, you can use the hex character constant \x9c to represent the
pound sign (). In Borland C++, you can put the pound sign into your program directly by pasting it
from the Windows Character Map accessory.*/
#include<iostream.h>
#include<conio.h>
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!1 pound = 20 shilling
!1 shilling = 12 pence
!so 1 pound = (20*12) 240 pence [in old system]
!also 1 pound = 100 pence [in new system]
!hence the transformation formula is :
!new_pence = (old_pence*100)/240
---------------------
!number of pence{old_pence} = (input_shillings*12) + input_pence
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n\n";
int pounds, shillings, pence;
do{
cout<<"Enter pounds : ";
cin >>pounds;
cout<<"Enter shillings : ";
cin >>shillings;
cout<<"Enter pence : ";
cin >>pence;
pence = ((shillings*12)+pence)*100/240;
//To make the programme more really (pence must not pass value 100).
if (pence >= 100){
//shillings here is only a gate, not by it's mean at all.
shillings = pence%100;
pounds += (pence-shillings)/100;
pence = shillings;}
cout<<"Decimal pounds = \x9c"<<pounds<<"."<<pence<<endl;
cout<<"\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*11. By default, output is right-justified in its field. You can left-justify text output using the
manipulator setiosflags(ios::left). (For now, dont worry about what this new notation means.) Use
this manipulator, along with setw(), to help generate the following output:

Last name First name Street address Town State
------------------
Jones Bernard 109 Pine Lane Littletown MI
OBrian Coleen 42 E. 99th Ave. Bigcity NY
Wong Harry 121-A Alabama St. Lakeville IL
*/
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n\n";
char *l_name[3] = {"Jones", "O'Brian", "Wong"},
*f_name[3] = {"Bernard", "Coleen", "Harry"},
*adress[3] = {"109 Pine Lane", "42 E. 99th Ave.", "121-A Alabama St."},
*town[3] = {"Littletown", "Bigcity", "Lakeville"},
*state[3] = {"MI", "NY", "IL"};

do{
cout<<setiosflags(ios::left)<<setw(11)<<"Last name"
<<setw(12)<<"First name"
<<setw(20)<<"Street adress"
<<setw(12) <<"Town"
<<setw(7) <<"State"
<<endl;
for(int i=0;i<60;i++) cout<<"-";
for(int j=0;j<3;j++){
cout<<endl<<setiosflags(ios::left)<<setw(11)<<l_name[j]
<<setw(12)<<f_name[j]
<<setw(20)<<adress[j]
<<setw(12)<<town[j]
<<setw(7) <<state[j]
<<endl;}
cout<<"\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*12. Write the inverse of Exercise 10, so that the user enters an amount in Great Britains new
decimal-pounds notation (pounds and pence), and the program converts it to the old pounds-
shillings-pence notation. An example of interaction with the program might be

Enter decimal pounds: 3.51
Equivalent in old notation = 3.10.2.

Make use of the fact that if you assign a floating-point value (say 12.34) to an integer variable, the
decimal fraction (0.34) is lost; the integer value is simply 12. Use a cast to avoid a compiler
warning. You can use statements like

float decpounds; // input from user (new-style pounds)
int pounds; // old-style (integer) pounds
float decfrac; // decimal fraction (smaller than 1.0)

pounds = static_cast<int>(decpounds); // remove decimal fraction
decfrac = decpounds - pounds; // regain decimal fraction

You can then multiply decfrac by 20 to find shillings. A similar operation obtains pence.*/
#include<iostream.h>
#include<conio.h>
//Old programme:
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!1 pound = 20 shilling
!1 shilling = 12 pence
!so 1 pound = (20*12) 240 pence [in old system]
!also 1 pound = 100 pence [in new system]
!hence the transformation formula is :
!new_pence = (old_pence*100)/240
---------------------
!number of pence{old_pence} = (input_shillings*12) + input_pence
!New: using the inverse function.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n\n";
float decpounds; // input from user (new-style pounds)
int pounds, shillings; // old-style (integer) pounds & shillings
float decfrac; // decimal fraction (smaller than 1.0)

do{
cout<<"Enter decimal pounds: ";
//cin >>pounds>>var_char>>decfrac; //I think this way is better!
cin >>decpounds;
pounds = static_cast<int>(decpounds); // remove decimal fraction
//user should enter valid data , pence entred smaller than 100.
decfrac = 240*(decpounds - pounds); // regain decimal fraction
shillings = (static_cast<int>(decfrac))%12; //Ignore fracions in pence.
decfrac = static_cast<int>((decfrac-shillings)/12); //Ignore fracions in pence.
cout<<"Equivalent in old notation = \x9c"<<pounds<<"."<<decfrac<<"."<<shillings<<endl;
cout<<"\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}
Amahdy at 2007-11-11 21:03:28 >
# 6 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
CHAPTER 3LOOPS AND DECISIONS

Questions:
----
1. A relational operator
a. assigns one operand to another.
b. yields a Boolean result.
c. compares two operands.
d. logically combines two operands.
2. Write an expression that uses a relational operator to return true if the variable george is not equal to sally.
3. Is 1 true or false?
4. Name and describe the usual purpose of three expressions in a for statement.
5. In a for loop with a multistatement loop body, semicolons should appear following
a. the for statement itself.
b. the closing brace in a multistatement loop body.
c. each statement within the loop body.
d. the test expression.
6. True or false: The increment expression in a for loop can decrement the loop variable.
7. Write a for loop that displays the numbers from 100 to 110.
8. A block of code is delimited by _________.
9. A variable defined within a block is visible
a. from the point of definition onward in the program.
b. from the point of definition onward in the function.
c. from the point of definition onward in the block.
d. throughout the function.
10. Write a while loop that displays the numbers from 100 to 110.
11. True or false: Relational operators have a higher precedence than arithmetic operators.
12. How many times is the loop body executed in a do loop?
13. Write a do loop that displays the numbers from 100 to 110.
14. Write an if statement that prints Yes if a variable age is greater than 21.
15. The library function exit() causes an exit from
a. the loop in which it occurs.
b. the block in which it occurs.
c. the function in which it occurs.
d. the program in which it occurs.
16. Write an if...else statement that displays Yes if a variable age is greater than 21, and displays No otherwise.
17. The getche() library function
a. returns a character when any key is pressed.
b. returns a character when [Enter] is pressed.
c. displays a character on the screen when any key is pressed.
d. does not display a character on the screen.
18. What is the character obtained from cin when the user presses the [Enter] key?
19. An else always matches the _________ if, unless the if is _________.
20. The else...if construction is obtained from a nested if...else by ________________.
21. Write a switch statement that prints Yes if a variable ch is y, prints No if ch is n, and prints Unknown response otherwise.
22. Write a statement that uses a conditional operator to set ticket to 1 if speed is greater than 55, and to 0 otherwise.
23. The && and || operators
a. compare two numeric values.
b. combine two numeric values.
c. compare two Boolean values.
d. combine two Boolean values.
24. Write an expression involving a logical operator that is true if limit is 55 and speed is greater than 55.
25. Arrange in order of precedence (highest first) the following kinds of operators: logical, unary, arithmetic, assignment, relational, conditional.
26. The break statement causes an exit
a. only from the innermost loop.
b. only from the innermost switch.
c. from all loops and switches.
d. from the innermost loop or switch.
27. Executing the continue operator from within a loop causes control to go to ________.
28. The goto statement causes control to go to
a. an operator.
b. a label.
c. a variable.
d. a function.
__________

My answers:
----
1. yields a Boolean result, compares two operands.
2. if(george != sally) op=true.
3. true.
4. definitions of some variavles, compare of operands to hold the exit for condition, the changes in variables in each loop.
5. each statement within the loop body, the test expression.
6. true.
7. for(int i=100; i<111; i++) cout<<i<<endl;
8. {}
9. from the point of definition onward in the function.
10. int i=110; while(i<111) cout<<i++<<endl;
11. false.
12. one time.
13. int i=110; do cout<<i++<<endl; while(i<111);
14. if(age>21) cout<<"Yes";
15. the program in which it occurs.
16. if(age>21) cout<<"Yes"; else cout<<"No";
17. returns a character when any key is pressed, displays a character on the screen when any key is pressed.
18. '\r'
19. opposit of the, done.
20. nested if contidtions.
21. switch(ch){case 'y': cout<<"Yes"; break; case 'n': cout<<"No"; break; default: cout<<"Unknown response";}
22. ticket = (speed>55) ? 1 : false;
23. combine two Boolean values.
24. if(limit == 55 && speed > 55) op = true;
25. ?.
26. from the innermost loop or switch.
27. begin of loop.
28. a label.
___________

Answers:
---
1. b, c
2. george != sally
3. 1 is true; only 0 is false.
4. The initialize expression initializes the loop variable, the test expression tests the loop variable, and the increment expression changes the loop variable.
5. c, d
6. True
7.
for(int j=100; j<=110; j++)
cout << endl << j;

8. braces (curly brackets)
9. c
10.
int j = 100;
while( j <= 110 )
cout << endl << j++;

11. False
12. At least once.
13.
int j = 100;
do
cout << endl << j++;
while( j <= 110 );

14.
if(age > 21)
cout << Yes;

15. d
16.
if( age > 21 )
cout << Yes;
else
cout << No;

17. a, c
18. \r
19. preceding, surrounded by braces
20. reformatting
21.
switch(ch)
{
case y:
cout << Yes;
break;
case n:
cout << No;
break;
default:
cout << Unknown response;
}

22. ticket = (speed > 55) ? 1 : 0;
23. d
24. limit == 55 && speed > 55
25. unary, arithmetic, relational, logical, conditional, assignment
26. d
27. the top of the loop
28. b
________
Amahdy at 2007-11-11 21:04:33 >
# 7 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
CHAPTER 3LOOPS AND DECISIONS codes;

/**1. Assume you want to generate a table of multiples of any given number. Write a program that
allows the user to enter the number, and then generates the table, formatting it into 10 columns and
20 lines. Interaction with the program should look like this (only the first three lines are shown):

Enter a number: 7

7 14 21 28 35 42 49 56 63 70
77 84 91 98 105 112 119 126 133 140
147 154 161 168 175 182 189 196 203 210
*/
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n\n";

int i, j, entred_int;

do{
cout<<"Enter a number: "; cin >>entred_int;
for(i=0; i<20; i++){for(j=0; j<10; j++) cout<<setw(7)<<(entred_int*(10*i+j+1)); cout<<endl;}
cout<<"\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/**2. Write a temperature-conversion program that gives the user the option of converting Fahrenheit
to Celsius or Celsius to Fahrenheit. Then carry out the conversion. Use floating-point numbers.
Interaction with the program might look like this:

Type 1 to convert Fahrenheit to Celsius,
2 to convert Celsius to Fahrenheit: 1
Enter temperature in Fahrenheit: 70
In Celsius thats 21.111111*/
#include<iostream.h>
#include<conio.h>

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n\n";

int choise; float temp;

do{
cout<<"Type 1 to convert Fahrenheit to Celsius,\n 2 to convert Celsius to Fahrenheit: ";
cin >>choise;
switch(choise){ //replacable by if ... else .
case 2:
cout<<"Enter temperature in Celsius: "; cin >>temp;
cout<<"In Fahrenheit that's "<<(9*temp/5)+32;
break;
case 1:
cout<<"Enter temperature in Fahrenheit: "; cin >>temp;
cout<<"In Celsius that's " <<((temp-32)*5)/9;
break;
default :
cout<<"Invalid choise try again !";}
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/**3. Operators such as >>, which read input from the keyboard, must be able to convert a series of
digits into a number. Write a program that does the same thing. It should allow the user to type up
to six digits, and then display the resulting number as a type long integer. The digits should be read
individually, as characters, using getche(). Constructing the number involves multiplying the existing
value by 10 and then adding the new digit. (Hint: Subtract 48 or 0 to go from ASCII to a
numerical digit.)
Heres some sample interaction:

Enter a number: 123456
Number is: 123456
*/
#include<iostream>
using namespace std; //to avoid cout interaction with while loop.
#include<conio.h>

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

int i; long _output; char char_input;

do{
cout<<"Enter a number (Maximum six characters): ";
_output = 0; i=0;
//ASCII('\r') == 13
while((char_input=getche()) != 13 && i<6){
_output = 10*_output + (char_input - 48);
i++;}
if(i == 6) cout<<"\b ";
cout<<"\nNumber is: "<<_output;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/**4. Create the equivalent of a four-function calculator. The program should request the user to
enter a number, an operator, and another number. (Use floating point.) It should then carry out the
specified arithmetical operation: adding, subtracting, multiplying, or dividing the two numbers. Use a
switch statement to select the operation. Finally, display the result.
When it finishes the calculation, the program should ask if the user wants to do another calculation.
The response can be y or n. Some sample interaction with the program might look like this:

Enter first number, operator, second number: 10 / 3
Answer = 3.333333
Do another (y/n)? y
Enter first number, operator, second number: 12 + 100
Answer = 112
Do another (y/n)? n
*/
#include<iostream>
using namespace std; //needed in asking() function.
#include<conio.h>
#include<stdlib.h>

void calcul(void); //calculations function.
void asking(void); //asking to continue function.

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

do{
calcul();
asking();
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

void calcul(void)
{
float num[2]; char operation;

cout<<"\nEnter first number, operator, second number: ";
cin >>num[0]>>operation>>num[1];
switch(operation){
case '+':
cout<<"Answer = "<<num[0] + num[1]<<endl;
break;
case '-':
cout<<"Answer = "<<num[0] - num[1]<<endl;
break;
case '*':
cout<<"Answer = "<<num[0] * num[1]<<endl;
break;
case '/':
if(num[1] != 0) cout<<"Answer = "<<num[0] / num[1]<<endl;
else {cout<<"Math error !"<<endl; calcul();}
break;
default:
cout<<"Unknow operator please try again !"<<endl;
calcul();}
}

void asking(void)
{
cout<<"\nDo another (y/n)? ";
switch(toupper(getche())){
case 'Y':
calcul();
asking();
break;
case 'N':
exit(1);
break;
default:
asking();}
}

/*5. Use for loops to construct a program that displays a pyramid of Xs on the screen. The pyramid
should look like this

X
XXX
XXXXX
XXXXXXX
XXXXXXXXX

except that it should be 20 lines high, instead of the 5 lines shown here. One way to do this is to nest
two inner loops, one to print spaces and one to print Xs, inside an outer loop that steps down the
screen from line to line.*/
#include<iostream.h>
#include<conio.h>

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

//Definition;

do{
for(int i=0; i<20; i++){
for(int X=0 ; X<20 ; X++) cout<<" "; //This line optional to make the pyramid on the midlle.
for(int j=20-i; j>0 ; j--) cout<<" ";
for(int k=0 ; k<2*i+1; k++) cout<<"X";
cout<<endl;}
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}
Amahdy at 2007-11-11 21:05:31 >
# 8 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
/*6. Modify the FACTOR program in this chapter so that it repeatedly asks for a number and
calculates its factorial, until the user enters 0, at which point it terminates. You can enclose the
relevant statements in FACTOR in a while loop or a do loop to achieve this effect.*/
#include<iostream>
using namespace std;
#include<conio.h>

// The FACTOR program:
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!#include <iostream>
!using namespace std;
!
!int main()
! {
! unsigned int numb;
! unsigned long fact=1; //long for larger numbers
!
! cout << Enter a number: ;
! cin >> numb; //get number
!
! for(int j=numb; j>0; j--) //multiply 1 by
! fact *= j; //numb, numb-1, ..., 2, 1
! cout << Factorial is << fact << endl;
! return 0;
! }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

unsigned int numb, i;
unsigned long fact;

cout<<"Enter a number: ";
cin >>numb;
do{
fact=1; i=0;
for(i=numb; i>0; i--) fact *= i;
cout<<"\n\nFactorial is "<<fact<<endl;
cout<<" !Enter 0 to exit or any other number to calculate it's factorial: ";
cin >>numb;
}while(numb!=0);
}

/*7. Write a program that calculates how much money youll end up with if you invest an amount of
money at a fixed interest rate, compounded yearly. Have the user furnish the initial amount, the
number of years, and the yearly interest rate in percent. Some interaction with the program might
look like this:

Enter initial amount: 3000
Enter number of years: 10
Enter interest rate (percent per year): 5.5
At the end of 10 years, you will have 5124.43 dollars.

At the end of the first year you have 3000 + (3000 * 0.055), which is 3165. At the end of the
second year you have 3165 + (3165 * 0.055), which is 3339.08. Do this as many times as there
are years. A for loop makes the calculation easy.*/
#include<iostream.h>
#include<conio.h>

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

int num_year; float init_amount, intrst_rate;

do{
cout<<"Enter initial amount : "; cin >>init_amount;
cout<<"Enter number of years : "; cin >>num_year ;
cout<<"Enter interest rate (percent per year): "; cin >>intrst_rate;
for(int i=0; i<num_year; i++) init_amount += init_amount*intrst_rate/100;
cout<<"At the end of "<<num_year
<<" years, you will have "<<init_amount
<<" dollars.";
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*8. Write a program that repeatedly asks the user to enter two money amounts expressed in old-
style British currency: pounds, shillings, and pence. (See Exercises 10 and 12 in Chapter 2, ++
Programming Basics.) The program should then add the two amounts and display the answer,
again in pounds, shillings, and pence. Use a do loop that asks the user if the program should be
terminated. Typical interaction might be

Enter first amount: 5.10.6
Enter second amount: 3.2.6
Total is 8.13.0
Do you wish to continue (y/n)?

To add the two amounts, youll need to carry 1 shilling when the pence value is greater than 11, and
carry 1 pound when there are more than 19 shillings.*/
#include<iostream.h>
#include<conio.h>

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

int m[2][3]; char sep; //m (money), sep (char_separator).

do{
cout<<"Enter first amount : \x9c";
cin >>m[0][0]>>sep>>m[0][1]>>sep>>m[0][2];
cout<<"Enter second amount: \x9c";
cin >>m[1][0]>>sep>>m[1][1]>>sep>>m[1][2];
m[0][0] += m[1][0]; m[0][1] += m[1][1]; m[0][2] += m[1][2];
if(m[0][2]>11){m[0][1] += static_cast<int>(m[0][2]/12); m[0][2] %= 12;}
if(m[0][1]>19){m[0][0] += static_cast<int>(m[0][1]/20); m[0][1] %= 20;}
cout<<"Total is : \x9c"<<m[0][0]<<sep<<m[0][1]<<sep<<m[0][2];
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*9. Suppose you give a dinner party for six guests, but your table seats only four. In how many ways
can four of the six guests arrange themselves at the table? Any of the six guests can sit in the first
chair. Any of the remaining five can sit in the second chair. Any of the remaining four can sit in the
third chair, and any of the remaining three can sit in the fourth chair. (The last two will have to
stand.) So the number of possible arrangements of six guests in four chairs is 6*5*4*3, which is
360. Write a program that calculates the number of possible arrangements for any number of guests
and any number of chairs. (Assume there will never be fewer guests than chairs.) Dont let this get
too complicated. A simple for loop should do it.*/
#include<iostream.h>
#include<conio.h>

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

int ch_num, gs_num, result;

do{
cout<<"Enter number of guests : \xdb "; cin >>gs_num;
cout<<"Enter number of chairs : \xdb "; cin >>ch_num;
result=1; for(int i=0; i<ch_num; i++) result*=(gs_num-i);
cout<<"The number of possible arrangements is : \xdb "<<result;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*10. Write another version of the program from Exercise 7 so that, instead of finding the final
amount of your investment, you tell the program the final amount and it figures out how many years it
will take, at a fixed rate of interest compounded yearly, to reach this amount. What sort of loop is
appropriate for this problem? (Dont worry about fractional years; use an integer value for the year.)*/
#include<iostream.h>
#include<conio.h>

//Old programme:
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~
#include<iostream.h>
#include<conio.h>

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

int num_year; float init_amount, intrst_rate;

do{
cout<<"Enter initial amount : "; cin >>init_amount;
cout<<"Enter number of years : "; cin >>num_year ;
cout<<"Enter interest rate (percent per year): "; cin >>intrst_rate;
for(int i=0; i<num_year; i++) init_amount += init_amount*intrst_rate/100;
cout<<"At the end of "<<num_year
<<" years, you will have "<<init_amount
<<" dollars.";
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~*/

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

int i; float init_amount, intrst_rate, finl_amount;

do{
cout<<"Enter initial amount : "; cin >>init_amount;
cout<<"Enter interest rate (percent per year): "; cin >>intrst_rate;
cout<<"Enter final amount : "; cin >>finl_amount;
i=0;
while(finl_amount>=init_amount) {finl_amount -= finl_amount*intrst_rate/100; i++;}
cout<<"Number of years is : "<<i;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}
Amahdy at 2007-11-11 21:06:41 >
# 9 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
/*11. Create a three-function calculator for old-style English currency, where money amounts are
specified in pounds, shillings, and pence. (See Exercises 10 and 12 in Chapter 2.) The calculator
should allow the user to add or subtract two money amounts, or to multiply a money amount by a
floating-point number. (It doesnt make sense to multiply two money amounts; there is no such thing
as square money. Well ignore division. Use the general style of the ordinary four-function
calculator in Exercise 4 in this chapter.)*/
#include<iostream.h>
#include<conio.h>

void chk_overs(void);
int m[3][3]; char c[3];

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

do{
cout<<"Enter the currency opperation: ";
cin >>m[0][0]>>c[0]>>m[0][1]>>c[1]>>m[0][2]>>c[2];
switch(c[2]){
case '+':
cin >>m[1][0]>>c[0]>>m[1][1]>>c[1]>>m[1][2];
m[0][0] += m[1][0]; m[0][1] += m[1][1]; m[0][2] += m[1][2];
chk_overs();
cout<<"Answer = "<<m[0][0]<<c[0]<<m[0][1]<<c[1]<<m[0][2];
break;
case '-':
cin >>m[1][0]>>c[0]>>m[1][1]>>c[1]>>m[1][2];
m[0][0] -= m[1][0]; m[0][1] -= m[1][1]; m[0][2] -= m[1][2];
chk_overs();
cout<<"Answer = "<<m[0][0]<<c[0]<<m[0][1]<<c[1]<<m[0][2];
break;
case '*':
cin >>m[1][0];
m[0][0] *= m[1][0]; m[0][1] *= m[1][0]; m[0][2] *= m[1][0];
chk_overs();
cout<<"Answer = "<<m[0][0]<<c[0]<<m[0][1]<<c[1]<<m[0][2];
break;
default :
cout<<"Syntex or operation error, check your inputs again.";}
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

void chk_overs(void)
{
if(m[0][2]>11){m[0][1] += static_cast<int>(m[0][2]/12); m[0][2] %= 12;}
if(m[0][1]>19){m[0][0] += static_cast<int>(m[0][1]/20); m[0][1] %= 20;}
}

/*12. Create a four-function calculator for fractions. (See Exercise 9 in Chapter 2, and Exercise 4 in
this chapter.) Here are the formulas for the four arithmetic operations applied to fractions:
Addition: a/b + c/d = (a*d + b*c) / (b*d)
Subtraction: a/b - c/d = (a*d - b*c) / (b*d)
Multiplication: a/b * c/d = (a*c) / (b*d)
Division: a/b / c/d = (a*d) / (b*c)

The user should type the first fraction, an operator, and a second fraction. The program should then
display the result and ask if the user wants to continue.*/
#include<iostream.h>
#include<conio.h>

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

int first[2], last[2];
char op[2];

do{
cout<<"Enter your task : ";
cin >>first[0]>>op[0]>>last[0]>>op[1]
>>first[1]>>op[0]>>last[1];
if(!last[0] || !last[1]) {cout<<"Illeagle fraction !"<<endl; op[1] = false;}
switch(op[1]) {
case '+':
cout<<"Answer = "<<(first[0]*last[1] + last[0]*first[1])<<op[0]<<(last[0]*last[1]);
break;
case '-':
cout<<"Answer = "<<(first[0]*last[1] - last[0]*first[1])<<op[0]<<(last[0]*last[1]);
break;
case '*':
cout<<"Answer = "<<first[0]*first[1]<<op[0]<<last[0]*last[1];
break;
case '/':
if(first[1] != 0) cout<<"Answer = "<<first[0]*last[1]<<op[0]<<first[1]*last[0];
else cout<<"Math error !"<<endl;
break;
default:
cout<<"Unknow operator please try again !"<<endl;}
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}
Amahdy at 2007-11-11 21:07:32 >
# 10 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
CHAPTER 4STRUCTURES

Questions:
----
1. A structure brings together a group of
a. items of the same data type.
b. related data items.
c. integers with user-defined names.
d. variables.
2. True or false: A structure and a class use similar syntax.
3. The closing brace of a structure is followed by a __________.
4. Write a structure specification that includes three variablesall of type intcalled hrs, mins, and secs. Call this structure time.
5. True or false: A structure declaration creates space in memory for a variable.
6. When accessing a structure member, the identifier to the left of the dot operator is the name of
a. a structure member.
b. a structure tag.
c. a structure variable.
d. the keyword struct.
7. Write a statement that sets the hrs member of the time2 structure variable equal to 11.
8. If you have three variables defined to be of type struct time, and this structure contains three int members, how many bytes of memory do the variables use together?
9. Write a definition that initializes the members of time1which is a variable of type struct time, as defined in Question 4to hrs = 11, mins = 10, secs = 59.
10. True or false: You can assign one structure variable to another, provided they are of the same type.
11. Write a statement that sets the variable temp equal to the paw member of the dogs member of the fido variable.
12. An enumeration brings together a group of
a. items of different data types.
b. related data variables.
c. integers with user-defined names.
d. constant values.
13. Write a statement that declares an enumeration called players with the values B1, B2, SS, B3, RF, CF, LF, P, and C.
14. Assuming the enum type players as declared in Question 13, define two variables joe and tom, and assign them the values LF and P, respectively.
15. Assuming the statements of Questions 13 and 14, state whether each of the following statements is legal.
a. joe = QB;
b. tom = SS;
c. LF = tom;
d. difference = joe - tom;
16. The first three enumerators of an enum type are normally represented by the values _________, _________, and _________.
17. Write a statement that declares an enumeration called speeds with the enumerators obsolete, single, and album. Give these three names the integer values 78, 45, and 33.
18. State the reason why
enum isWord{ NO, YES };
is better than
enum isWord{ YES, NO };
__________

My answers:
----
1. related data items, variables.
2. True.
3. ';'.
4. struct time {int hrs, mins, secs;};
5. False.
6. a structure variable.
7. time2.hrs=11;
8. 36.
9. time time1 = {11, 10, 59};
10. True.
11. temp=fido.dogs.paw;
12. integers with user-defined names, constant values.
13. enum players {B1, B2, SS, B3, RF, CF, LF, P, c};
14. players joe=LF, tom=P;
15. difference = joe - tom;
16. 0, 1, 2.
17. emun speeds {obsolete=78, single=45, album=33};
18. Normaly False is near to no and the first put in NO the same value of false, same thing for YES.
___________

Answers:
---
1. b, d
2. True
3. semicolon
4.
struct time
{
int hrs;
int mins;
int secs;
};

5. False; only a variable definition creates space in memory.
6. c
7. time2.hrs = 11;
8. 18 in 16-bit systems (3 structures times 3 integers times 2 bytes), or 36 in 32-bit systems
9. time time1 = { 11, 10, 59 };
10. True
11. temp = fido.dogs.paw;
12. c
13. enum players { B1, B2, SS, B3, RF, CF, LF, P, C };
14.
players joe, tom;
joe = LF;
tom = P;

15. a. No
b. Yes
c. No
d. Yes
16. 0, 1, 2
17. enum speeds { obsolete=78, single=45, album=33 };
18. Because false should be represented by 0.
________
Amahdy at 2007-11-11 21:08:40 >
# 11 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
CHAPTER 4STRUCTURES codes;

/**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
*/
#include<iostream.h>
#include<conio.h>

struct phone{int area_code, exchange, number;};
void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

phone input, mine={212, 767, 8900};

do{
cout<<"Enter your area code, exchange, and number: ";
cin >>input.area_code>>input.exchange>>input.number;
cout<<"My number is ("<<mine.area_code<<") "<<mine.exchange<<"-"<<mine.number<<endl;
cout<<"Your number is ("<<input.area_code<<") "<<input.exchange<<"-"<<input.number;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/**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 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
*/
#include<iostream.h>
#include<conio.h>

struct point{int x, y;};
void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

point p1, p2, sum;

do{
cout<<"Enter coordinates for p1: "; cin >>p1.x>>p1.y;
cout<<"Enter coordinates for p2: "; cin >>p2.x>>p2.y;
sum.x=p1.x+p2.x; sum.y=p1.y+p2.y;
cout<<"Coordinates of p1+p2 are: "<<sum.x<<", "<<sum.y;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/**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.*/
#include<iostream.h>
#include<conio.h>

struct Distance{int feet; float inches;};
struct Volume{Distance x, y, z;};
void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

Volume dimension; char c;

do{
cout<<"Enter x, y & z ...\n(EX: 3.6=3 feet and 6 inches, default: 'x.0 y.0 z.0' x, y & z are in feet) : \n";
cin >>dimension.x.feet>>c>>dimension.x.inches
>>dimension.y.feet>>c>>dimension.y.inches
>>dimension.z.feet>>c>>dimension.z.inches;
/*float result=(dimension.x.feet+dimension.x.inches/12)*
(dimension.y.feet+dimension.y.inches/12)*
(dimension.z.feet+dimension.z.inches/12);*/
cout<<"the volume is : "
<<(dimension.x.feet+dimension.x.inches/12)*
(dimension.y.feet+dimension.y.inches/12)*
(dimension.z.feet+dimension.z.inches/12);



cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*4. Create a structure called employee that contains two members: an employee number (type int)
and the employees 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.*/
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

struct employee{int number; float compensation;};
void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

employee e[3]; int i;

do{
for(i=0; i<3; i++) {
cout<<"Enter the number of employee number "<<i+1<<" : "; cin>>e[i].number;
cout<<"Enter the compensation of employee number "<<i+1<<" : "; cin>>e[i].compensation;}
cout<<"Employee number"<<" Employee compensation\n";
for(i=0; i<3; i++) cout<<setw(15)<<e[i].number<<setw(24)<<e[i].compensation<<endl;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*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. */
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

struct date{int day; int month; int year;};
void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

date x; char c;

do{
cout<<"Enter the date : "; cin >>x.day>>c>>x.month>>c>>x.year;
cout<<"The date is : "; cout<<x.day<<c<<x.month<<c<<x.year;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}
Amahdy at 2007-11-11 21:09:43 >
# 12 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
/*6. We said earlier that C++ I/O statements dont 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 users 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.

Youll probably need two switch statements: one for input and one for output.*/
#include<iostream>
using namespace std;
#include<conio.h>

enum etype{laborer, secretary, manager, accountant, executive, researcher};
void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

etype x; char *ret;

do{
cout<<"Enter employee type (first letter only)"<<endl
<<"(laborer, secretary, manager, accountant, executive, researcher): ";
switch(getche()){
case 'l': x=laborer ; break;
case 's': x=secretary ; break;
case 'm': x=manager ; break;
case 'a': x=accountant; break;
case 'e': x=executive ; break;
case 'r': x=researcher;}
switch(x){
case 0: ret = "laborer" ; break;
case 1: ret = "secretary" ; break;
case 2: ret = "manager" ; break;
case 3: ret = "accountant"; break;
case 4: ret = "executive" ; break;
case 5: ret = "researcher";}
cout<<"\nEmployee type is "<<ret<<".";
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*7. Add a variable of type enum etype (see Exercise 5), and another variable of type struct date (see
Exercise 3) 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 employees
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.*/
#include<iostream>
#include<conio.h>
#include<iomanip>
using namespace std;

enum etype{laborer, secretary, manager, accountant, executive, researcher};
struct date{int day; int month; int year;};
struct employee{int number; float compensation; date d; char *ret;};
void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

employee e[3]; int i; char c; etype x;
do{
for(i=0; i<3; i++) {
cout<<"\nEnter the number of employee number "<<i+1<<" : "; cin>>e[i].number;
cout<<"Enter the compensation of employee number "<<i+1<<" : "; cin>>e[i].compensation;
cout<<"Enter employee type (first letter only) of employee number "<<i+1<<" : "<<endl
<<"(laborer, secretary, manager, accountant, executive, researcher): ";
switch(getche()){
case 'l': x=laborer ; break;
case 's': x=secretary ; break;
case 'm': x=manager ; break;
case 'a': x=accountant; break;
case 'e': x=executive ; break;
case 'r': x=researcher;}
switch(x){
case 0: e[i].ret = "laborer" ; break;
case 1: e[i].ret = "secretary" ; break;
case 2: e[i].ret = "manager" ; break;
case 3: e[i].ret = "accountant"; break;
case 4: e[i].ret = "executive" ; break;
case 5: e[i].ret = "researcher"; break;
default: e[i].ret = "Unknow";}
cout<<"\nEnter the date of employee number "<<i+1<<" : "; cin >>e[i].d.day>>c>>e[i].d.month>>c>>e[i].d.year;}
cout<<"\nEmployee number"<<" compensation"<<" type"<<" date of first employment"<<endl;
for(i=0; i<3; i++) cout<<setw(15)<<e[i].number
<<setw(15)<<e[i].compensation
<<setw(15)<<e[i].ret
<<setw(21)<<e[i].d.day<<c<<e[i].d.month<<c<<e[i].d.year<<endl;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*8. Start with the fractionadding 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 fractions numerator and denominator
(both type int). All fraction-related data should be stored in structures of this type.*/
#include<iostream>
#include<conio.h>
using namespace std;

struct fraction{int numerator; int denominator;};
void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;
fraction equ[2];
char operation;

do{
cout<<"Enter first fraction: ";
cin >>equ[0].numerator>>operation>>equ[0].denominator; //if (operation != '/') {raise error event}
cout<<"Enter second fraction: ";
cin >>equ[1].numerator>>operation>>equ[1].denominator; //if (operation != '/') {raise error event}
cout<<"Sum = "<<(equ[0].numerator*equ[1].denominator+equ[0].denominator*equ[1].numerator)
<<operation<<(equ[0].denominator*equ[1].denominator)<<endl;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*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
*/
#include<iostream>
#include<conio.h>
using namespace std;

struct time{int hours; int minutes; int seconds;};
void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

time t1; char c;

do{
cout<<"Enter a time value in hours, minutes, and seconds [hh:mm:ss] format: ";
cin >>t1.hours>>c>>t1.minutes>>c>>t1.seconds;
cout<<"The total number of seconds is: "<<t1.hours*3600 + t1.minutes*60 + t1.seconds;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*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 request 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.*/
#include<iostream>
#include<conio.h>
using namespace std;

struct sterling{int pounds; int shillings; int pence;};
void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

float decpounds; float decfrac; //From old programme.
sterling s1;

do{
cout<<"Enter a money amount in new-style decimal pounds: ";
cin >>decpounds;
s1.pounds = static_cast<int>(decpounds);
decfrac = 240*(decpounds-s1.pounds);
s1.shillings = (static_cast<int>(decfrac))%12; //Ignore fracions in pence.
decfrac = static_cast<int>((decfrac-s1.shillings)/12); //Ignore fracions in pence.
cout<<"Equivalent in old notation = \x9c"<<s1.pounds<<"."<<decfrac<<"."<<s1.shillings<<endl;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}
Amahdy at 2007-11-11 21:10:37 >
# 13 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
/*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 hours-minutes-seconds, stores the result in a
time structure, and finally displays the result in 12:59:59 format.*/
#include<iostream>
#include<conio.h>
using namespace std;

struct time{int hours; int minutes; int seconds;};
void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

time t1, t2, t3; char c; long tmp; //t3 coz he want to store the result in variable.

do{
cout<<"In [hh:mm:ss] format;\n";
cout<<"Enter first time value : "; cin >>t1.hours>>c>>t1.minutes>>c>>t1.seconds;
cout<<"Enter second time value: "; cin >>t2.hours>>c>>t2.minutes>>c>>t2.seconds;
tmp=t1.hours*3600+t1.minutes*60+t1.seconds+t2.hours*3600+t2.minutes*60+t2.seconds;
t3.seconds=tmp%60; t3.minutes=((tmp-t3.seconds)%3600)/60; t3.hours=tmp/3600;
//those lines for true input at first then true output.
if(t3.seconds>59) {t3.seconds-=59; t3.minutes++;} //Check seconds over.
if(t3.minutes>59) {t3.minutes-=59; t3.hours++;} //Check minutes over.
//hours check not needed .. at 25 hours I haven't a format for days.
cout<<"The result is: "<<t3.hours<<":"<<t3.minutes<<":"<<t3.seconds;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*12. 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.*/
#include<iostream>
#include<conio.h>
using namespace std;

struct fraction{int numerator; int denominator;};
void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

fraction f[2]; char c, op;

do{
cout<<"Enter your task : ";
cin >>f[0].numerator>>c>>f[0].denominator>>op>>f[1].numerator>>c>>f[1].denominator;
if(!f[0].denominator || !f[1].denominator) {cout<<"Illeagle fraction !"<<endl; op=false;}
switch(op) {
case '+':
cout<<"Answer = "<<(f[0].numerator*f[1].denominator+f[0].denominator*f[1].numerator)<<c
<<(f[0].denominator*f[1].denominator); break;
case '-':
cout<<"Answer = "<<(f[0].numerator*f[1].denominator-f[0].denominator*f[1].numerator)<<c
<<(f[0].denominator*f[1].denominator); break;
case '*':
cout<<"Answer = "<<f[0].numerator*f[1].numerator<<c<<f[0].denominator*f[1].denominator; break;
case '/':
if(f[0].numerator != 0) cout<<"Answer = "<<f[0].numerator*f[1].denominator<<c
<<f[1].numerator*f[0].denominator;
else cout<<"Math error !"<<endl; break;
default:
cout<<"Unknow operator please try again !"<<endl;}
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}
Amahdy at 2007-11-11 21:11:38 >
# 14 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
CHAPTER 5FUNCTIONS

Questions:
----
1. A functions single most important role is to
a. give a name to a block of code.
b. reduce program size.
c. accept arguments and provide a return value.
d. help organize a program into conceptual units.
2. A function itself is called the function d_________.
3. Write a function called foo() that displays the word foo.
4. A one-statement description of a function is referred to as a function d_________ or a p_________.
5. The statements that carry out the work of the function constitute the function _________.
6. A program statement that invokes a function is a function _________.
7. The first line of a function definition is referred to as the _________.
8. A function argument is
a. a variable in the function that receives a value from the calling program.
b. a way that functions resist accepting the calling programs values.
c. a value sent to the function by the calling program.
d. a value returned by the function to the calling program.
9. True or false: When arguments are passed by value, the function works with the original arguments in the calling program.
10. What is the purpose of using argument names in a function declaration?
11. Which of the following can legitimately be passed to a function?
a. A constant
b. A variable
c. A structure
d. A header file
12. What is the significance of empty parentheses in a function declaration?
13. How many values can be returned from a function?
14. True or false: When a function returns a value, the entire function call can appear on the right side of the equal sign and be assigned to another variable.
15. Where is a functions return type specified?
16. A function that doesnt return anything has return type _________.
17. Heres a function:
int times2(int a)
{
return (a*2);
}

Write a main() program that includes everything necessary to call this function.
18. When an argument is passed by reference,
a. a variable is created in the function to hold the arguments value.
b. the function cannot access the arguments value.
c. a temporary variable is created in the calling program to hold the arguments value.
d. the function accesses the arguments original value in the calling program.
19. What is a principle reason for passing arguments by reference?
20. Overloaded functions
a. are a group of functions with the same name.
b. all have the same number and types of arguments.
c. make life simpler for programmers.
d. may fail unexpectedly due to stress.
21. Write declarations for two overloaded functions named bar(). They both return type int. The first takes one argument of type char, and the second takes two arguments of type char. If this is impossible, say why.
22. In general, an inline function executes _________ than a normal function, but requires _________ memory.
23. Write the declarator for an inline function named foobar() that takes one argument of type float and returns type float.
24. A default argument has a value that
a. may be supplied by the calling program.
b. may be supplied by the function.
c. must have a constant value.
d. must have a variable value.
25. Write a declaration for a function called blyth() that takes two arguments and returns type char. The first argument is type int, and the second is type float with a default value of 3.14159.
26. Storage class is concerned with the _________ and _________ of a variable.
27. What functions can access an external variable that appears in the same file with them?
28. What functions can access an automatic variable?
29. A static automatic variable is used to
a. make a variable visible to several functions.
b. make a variable visible to only one function.
c. conserve memory when a function is not executing.
d. retain a value when a function is not executing.
30. In what unusual place can you use a function call when a function returns a value by reference?
__________

My answers:
----
1. reduce program size, help organize a program into conceptual units.
2. definition.
3. void foo(void) {cout<<"foo"; }
4. declairation, property value.
5. work.
6. caller.
7. function name.
8. a variable in the function that receives a value from the calling program, a value sent to the function by the calling program.
9. False.
10. Facilite knowing the concept of argument that I'll pass to the function.
11. A constant, A variable, A structure.
12. void.
13. one.
14. True.
15. before it's name.
16. void.
17. void main(void) {int a, time_two=times2(a);}
18. the function accesses the arguments original value in the calling program.
19. Use the original variable, not copy large values & return many different parammeters.
20. are a group of functions with the same name, make life simpler for programmers.
21. int bar(char); int bar(char, char);
22. faster, more.
23. inline float foobar(float);
24. may be supplied by the calling program, may be supplied by the function.
25. char blyth(int, float=3.14159);
26. ?, ?.
27. All defined function.
28. Functions that contains in their variables definition the "auto" keyword.
29. retain a value when a function is not executing.
30. As assigned value to it.
___________

Answers:
---
1. d (half credit for b)
2. definition
3.
void foo()
{
cout << foo;
}

4. declaration, prototype
5. body
6. call
7. declarator
8. c
9. False
10. To clarify the purpose of the arguments.
11. a, b, c
12. Empty parentheses mean the function takes no arguments.
13. one
14. True
15. At the beginning of the declaration and declarator.
16. void
17.
main()
{
int times2(int); // prototype
int alpha = times2(37); // function call
}

18. d
19. To modify the original argument (or to avoid copying a large argument).
20. a, c
21.
int bar(char);
int bar(char, char);

22. faster, more
23. inline float foobar(float fvar)
24. a, b
25. char blyth(int, float=3.14159);
26. visibility, lifetime
27. Those functions defined following the variable definition.
28. The function in which it is defined.
29. b, d
30. On the left side of the equal sign.
________
Amahdy at 2007-11-11 21:12:45 >
# 15 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
CHAPTER 5FUNCTIONS code;

/**1. 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.*/
#include<iostream>
#include<conio.h>
using namespace std;

float circarea(float radius);

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// circarea.cpp
// demonstrates floating point variables
#include <iostream> //for cout, etc.
using namespace std;

int main()
{
float rad; //variable of type float
const float PI = 3.14159F; //type const float

cout << "Enter radius of circle: "; //prompt
cin >> rad; //get radius
float area = PI * rad * rad; //find area
cout << "Area is " << area << endl; //display answer
return 0;
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

float rad;

do{
cout<<"Enter radius of circle: "; cin>> rad;
cout <<"Area is "<<circarea(rad);
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

float circarea(float radius) { return 3.14159F*radius*radius;}

/**2. 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.*/
#include<iostream>
#include<conio.h>
using namespace std;

double power(double n, int p=2);

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

double n; int p=2;

do{
cout<<"Enter n: "; cin>> n;
cout<<"Enter p: "; cin>> p;
cout <<"The power is "<<power(n, p);
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

double power(double n, int p){ for(int ret=1; p>0; p--) ret*=n; return ret;}

/**3. 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.*/
#include<iostream>
#include<conio.h>
using namespace std;

bool zeroSmaller(int& n1, int& n2);

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

int n1, n2;

do{
cout<<"Enter n1: "; cin>> n1;
cout<<"Enter n2: "; cin>> n2;
cout <<"The number assigned to zero is ";
if(zeroSmaller(n1, n2)) cout<<"n1"; else cout<<"n2";
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

bool zeroSmaller(int& n1, int& n2){
if(n1<n2) {n1=0; return true;}
else {n2=0;return false;}}

/**4. 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.).*/
#include<iostream>
#include<conio.h>
using namespace std;

int distWatch(int d1, int d2);

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

int d1, d2;

do{
cout<<"Enter d1: "; cin>> d1;
cout<<"Enter d2: "; cin>> d2;
cout <<"The largest distance is "<<distWatch(d1, d2);
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

int distWatch(int d1, int d2){ if(d1<d2) return d2; else return d1;}

/*5. Write a function called hms_to_secs() that takes three int valuesfor hours, minutes, and
secondsas 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.*/
#include<iostream>
#include<conio.h>
using namespace std;

long hms_to_secs(int hours, int minutes, int seconds);

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

int h, m, s; char sep;

do{
cout<<"Enter the time in format hh:mm:ss : "; cin>>h>>sep>>m>>sep>>s;
cout <<"The equivalent time in seconds is : "<<hms_to_secs(h, m, s);
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

long hms_to_secs(int hours, int minutes, int seconds){ return
seconds+minutes*60+hours*3600;}
Amahdy at 2007-11-11 21:13:42 >
# 16 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
/*6. Start with the program from Exercise 11, 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 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. */
#include<iostream>
#include<conio.h>
using namespace std;

struct time{int hours; int minutes; int seconds;};
long time_to_secs(time t);
time secs_to_time(long s);

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

time t1, t2, t3; char c;

do{
cout<<"In [hh:mm:ss] format;\n";
cout<<"Enter first time value : "; cin >>t1.hours>>c>>t1.minutes>>c>>t1.seconds;
cout<<"Enter second time value: "; cin >>t2.hours>>c>>t2.minutes>>c>>t2.seconds;
t3=secs_to_time(time_to_secs(t1)+time_to_secs(t2));
cout<<"The result is: "<<t3.hours<<":"<<t3.minutes<<":"<<t3.seconds;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

long time_to_secs(time t){ return t.hours*3600+t.minutes*60+t.seconds;}
time secs_to_time(long s){
time t;
t.seconds=s%60; t.minutes=((s-t.seconds)%3600)/60; t.hours=s/3600;
if(t.seconds>59) {t.seconds-=59; t.minutes++;} //Check seconds over.
if(t.minutes>59) {t.minutes-=59; t.hours++;} //Check minutes over.
return t;
}

/*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.*/
#include<iostream>
#include<conio.h>
using namespace std;

double power(double n, int p=2);
char power(char n, int p=2);
int power(int n, int p=2);
long power(long n, int p=2);
float power(float n, int p=2);

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

char sep; int p=2; double d_n; char c_n; int i_n; long l_n; float f_n;

do{
cout<<"In [n^p] format;\n";
cout<<"Enter a double type n : "; cin >>d_n>>sep>>p;
cout<<"The power is "<<power(d_n, p)<<endl;
cout<<"Enter a char type n : "; cin >>c_n>>sep>>p;
cout<<"The power is "<<power(c_n, p)<<endl;
cout<<"Enter a int type n : "; cin >>i_n>>sep>>p;
cout<<"The power is "<<power(i_n, p)<<endl;
cout<<"Enter a long type n : "; cin >>l_n>>sep>>p;
cout<<"The power is "<<power(l_n, p)<<endl;
cout<<"Enter a float type n : "; cin >>f_n>>sep>>p;
cout<<"The power is "<<power(f_n, p)<<endl;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

double power(double n, int p){ for(int ret=1; p>0; p--) ret*=n; return ret;}
char power(char n, int p){ for(int ret=1; p>0; p--) ret*=n; return ret;}
int power(int n, int p){ for(int ret=1; p>0; p--) ret*=n; return ret;}
long power(long n, int p){ for(int ret=1; p>0; p--) ret*=n; return ret;}
float power(float n, int p){ for(int ret=1; p>0; p--) ret*=n; return ret;}

/*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.) Youll need to decide how to pass the arguments. Create a main() program to exercise the
function.*/
#include<iostream>
#include<conio.h>
using namespace std;

void swap(int& a, int& b);

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

int a, b;

do{
cout<<"Enter a : "; cin >>a;
cout<<"Enter b : "; cin >>b; swap(a, b);
cout<<"Now a value is : "<<a<<" and b value is : "<<b;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

void swap(int& a, int& b){int c=a; a=b; b=c;}

/*9. This exercise is similar to Exercise 8, except that instead of two int variables, have the swap()
function interchange two struct time values (see Exercise 6).*/
#include<iostream>
#include<conio.h>
using namespace std;

struct time{int hours; int minutes; int seconds;};
void swap(time& t1, time& t2);

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

time t1, t2; char c;

do{
cout<<"In [hh:mm:ss] format;\n";
cout<<"Enter first time value : "; cin >>t1.hours>>c>>t1.minutes>>c>>t1.seconds;
cout<<"Enter second time value: "; cin >>t2.hours>>c>>t2.minutes>>c>>t2.seconds;
swap(t1, t2);
cout<<"Now first time is : " <<t1.hours<<c<<t1.minutes<<c<<t1.seconds
<<" and second time is : "<<t2.hours<<c<<t2.minutes<<c<<t2.seconds;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

void swap(time& a, time& b){time c=a; a=b; b=c;}

/*10. 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, or whatever. Write a main() program that calls this function at
least 10 times. Try implementing this function in two different ways. First, use an external variable to
store the count. Second, use a local static variable. Which is more appropriate? Why cant you use
an automatic variable?*/
#include<iostream>
#include<conio.h>
using namespace std;

void caller_counter(void);

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

int outer_counter=0;

do{
outer_counter++; caller_counter();
cout<<"\nThe main programme counter value is: "<<outer_counter;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

void caller_counter(void){
//I can't use an automatic variable coz it's created once I call the function only.
static int inner_counter=0; inner_counter++;
cout<<"I have been called "<<inner_counter<<" times";}
Amahdy at 2007-11-11 21:14:42 >
# 17 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
/*11. Write a program, based on the sterling structure of Exercise 10 in Chapter 4, Structures, 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.*/
#include<iostream>
#include<conio.h>
using namespace std;

struct sterling{int pounds; int shillings; int pence;};
sterling psp_to_sterling(int pounds, int shillings, int pence);
sterling sterling_add(sterling s1, sterling s2);
void sterling_disp(sterling s);
char c;

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

int x, y, z; sterling x1, x2;

do{
cout<<"In [9:19:11] format;\n";
cout<<"Enter first money amount in old-style British : \x9c";
cin>>x>>c>>y>>c>>z; x1=psp_to_sterling(x, y, z);
cout<<"Enter second money amount in old-style British : \x9c";
cin>>x>>c>>y>>c>>z; x2=psp_to_sterling(x, y, z);
sterling_disp(sterling_add(x1, x2));
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

sterling psp_to_sterling(int pounds, int shillings, int pence){
sterling x; x.pounds=pounds; x.shillings=shillings; x.pence=pence; return x;}

sterling sterling_add(sterling s1, sterling s2){
s1.pounds += s2.pounds; s1.shillings += s2.shillings; s1.pence += s2.pence;
if(s1.pence>11){s1.shillings += static_cast<int>(s1.pence/12); s1.pence %= 12;}
if(s1.shillings>19){s1.pounds += static_cast<int>(s1.shillings/20); s1.shillings %= 20;}
return s1;}

void sterling_disp(sterling s){
cout<<"Total is : \x9c"
<<s.pounds<<c<<s.shillings<<c<<s.pence;}

/*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.*/
#include<iostream>
#include<conio.h>
using namespace std;

struct fraction{int numerator; int denominator;};
fraction fadd(fraction a, fraction b);
fraction fsub(fraction a, fraction b);
fraction fmul(fraction a, fraction b);
fraction fdiv(fraction a, fraction b);

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

fraction f[3]; char c, op;

do{
cout<<"Enter your task : ";
cin >>f[0].numerator>>c>>f[0].denominator>>op>>f[1].numerator>>c>>f[1].denominator;
if(!f[0].denominator || !f[1].denominator) {cout<<"Illeagle fraction !"<<endl; op=false;}
switch(op) {
case '+': f[2]=fadd(f[0], f[1]); break;
case '-': f[2]=fsub(f[0], f[1]); break;
case '*': f[2]=fmul(f[0], f[1]); break;
case '/': f[2]=fdiv(f[0], f[1]); break;
default: cout<<"Unknow operator please try again !"<<endl;}
cout<<"Answer = "<<f[2].numerator<<c<<f[2].denominator;
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

fraction fadd(fraction a, fraction b){
fraction f;
f.numerator =a.numerator*b.denominator+a.denominator*b.numerator;
f.denominator=a.denominator*b.denominator; return f;}

fraction fsub(fraction a, fraction b){
fraction f;
f.numerator =a.numerator*b.denominator-a.denominator*b.numerator;
f.denominator=a.denominator*b.denominator; return f;}

fraction fmul(fraction a, fraction b){
fraction f;
f.numerator =a.numerator*b.numerator;
f.denominator=a.denominator*b.denominator; return f;}

fraction fdiv(fraction a, fraction b){
fraction f;
if(b.numerator != 0){
f.numerator =a.numerator*b.denominator;
f.denominator=b.numerator*a.denominator;}
else cout<<"Math error !"<<endl; return f;}
Amahdy at 2007-11-11 21:15:44 >
# 18 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
CHAPTER 6OBJECTS AND CLASSES

Questions:
----
1. What is the purpose of a class declaration?
2. A ________ has the same relation to an ________ that a basic data type has to a variable of that type.
3. In a class declaration, data or functions designated private are accessible
a. to any function in the program.
b. only if you know the password.
c. to member functions of that class.
d. only to public members of the class.
4. Write a class declaration that creates a class called leverage with one private data member, crowbar, of type int and one public function whose declaration is void pry().
5. True or false: Data items in a class must be private.
6. Write a statement that defines an object called lever1 of the leverage class described in Question 4.
7. The dot operator (or class member access operator) connects the following two entities (reading from left to right):
a. A class member and a class object
b. A class object and a class
c. A class and a member of that class
d. A class object and a member of that class
8. Write a statement that executes the pry() function in the lever1 object, as described in Questions 4 and 6.
9. Member functions defined inside a class declaration are ________ by default.
10. Write a member function called getcrow() for the leverage class described in Question 4. This function should return the value of the crowbar data. Assume the function is defined within the class declaration.
11. A constructor is executed automatically when an object is ________.
12. A constructors name is the same as _________.
13. Write a constructor that initializes to 0 the crowbar data, a member of the leverage class described in Question 4. Assume the constructor is defined within the class declaration.
14. True or false: In a class you can have more than one constructor with the same name.
15. A member function can always access the data
a. in the object of which it is a member.
b. in the class of which it is a member.
c. in any object of the class of which it is a member.
d. in the public part of its class.
16. Assume the member function getcrow() described in Question 10 is defined outside the class declaration. Write the declaration that goes inside the class declaration.
17. Write a revised version of the getcrow() member function from Question 10 that is defined outside the class declaration.
18. The only technical difference between structures and classes in C++ is that _________.
19. If three objects of a class are defined, how many copies of that classs data items are stored in memory? How many copies of its member functions?
20. Sending a message to an object is the same as _________.
21. Classes are useful because they
a. are removed from memory when not in use.
b. permit data to be hidden from other classes.
c. bring together all aspects of an entity in one place.
d. can closely model objects in the real world.
22. True or false: There is a simple but precise methodology for dividing a realworld programming problem into classes.
23. For the object for which it was called, a const member function
a. can modify both const and nonconst member data.
b. can modify only const member data.
c. can modify only nonconst member data.
d. can modify neither const nor nonconst member data.
24. True or false: If you declare a const object, it can only be used with const member functions.
25. Write a declaration (not a definition) for a const void function called aFunc() that takes one const argument called jerry of type float.
__________

My answers:
----
1. Manage objects formation.
2. Class, Object.
3. to member functions of that class.
4. class leverage{int crowbar; public: void pry();};
5. False.
6. leverage lever1;
7. A class object and a member of that class.
8. lever1.pry();
9. private.
10. int getcrow(){ return crowbar;}
11. defined.
12. class.
13. levrage(): crowbar(0){}
14. True.
15. in the object of which it is a member.
16. int getcrow();
17. int leverage::getcrow(){ return crowbar;}
18. members are by default public in struct, and private in class.
19. 3, 1.
20. passing to a function.
21. permit data to be hidden from other classes, bring together all aspects of an entity in one place, can closely model objects in the real world.
22. True.
23. can modify neither const nor nonconst member data.
24. False.
25. void aFunc(const float jerry) const;
___________

Answers:
---
1. A class declaration describes how objects of a class will look when they are created.
2. class, object
3. c
4.
class leverage
{
private:
int crowbar;
public:
void pry();
};

5. False; both data and functions can be private or public.
6. leverage lever1;
7. d
8. lever1.pry();
9. inline (also private)
10.
int getcrow()
{ return crowbar; }

11. created (defined)
12. the class of which it is a member
13.
leverage()
{ crowbar = 0; }

14. True
15. a
16. int getcrow();
17.
int leverage::getcrow()
{ return crowbar; }

18. member functions and data are, by default, public in structures but private in classes
19. three, one
20. calling one of its member functions
21. b, c, d
22. False; trial and error may be necessary.
23. d
24. True
25. void aFunc(const float jerry) const;
________
Amahdy at 2007-11-11 21:16:44 >
# 19 Re: C++ solutions for : [Object-Oriented Programming in C++, Third Edition]
CHAPTER 6OBJECTS AND CLASSES codes;

/**1. Create a class that imitates part of the functionality of the basic data type int.Call the class Int
(note different spelling). 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 (it looks just like an int), and to add two
Int values.
Write a program that exercises this class by creating two initialized and one uninitialized Int values,
adding these two initialized values and placing the response in the uninitialized value, and then
displaying this result.*/
#include<iostream>
#include<conio.h>
using namespace std;

class Int{
int int_var;
public:
Int(): int_var(0){}
Int(int begin): int_var(begin){}
void display() const{ cout<<int_var;}
void add(Int x, Int y){ int_var=x.int_var+y.int_var;}
};

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

Int a=5, b=7, c;

do{
c.add(a,b);
c.display();
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/**2. Imagine a tollbooth at a bridge. Cars passing by the booth are expected to pay a 50 cent toll.
Mostly they do, but sometimes a car goes by without paying. The tollbooth keeps track of the
number of cars that have 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 of these to 0. A member function called payingCar() increments the car
total and adds 0.50 to the cash total. Another function, called nopayCar(), increments the car total
but adds nothing to the cash total. Finally, a member function called display() displays the two totals.
Make appropriate member functions const.
Include a program to test this class. This program should allow the user to push one key to count a
paying car, and another to count a nonpaying car. Pushing the [Escape] key should cause the
program to print out the total cars and total cash and then exit. */
#include<iostream>
#include<conio.h>
using namespace std;

class tollBooth{
unsigned int num_cars;
double money_amount;
public:
tollBooth(): num_cars(0), money_amount(0) {}
void payingCar(){ num_cars++; money_amount+=.5;}
void nopayCar(){ num_cars++;}
void display() const {
cout<<"\rTotal number of cars is: "<<num_cars;
cout<<"\nTotal money amount is : "<<money_amount;}
};

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

tollBooth x;

do{
for(;;){
switch(toupper(getch())){
case('P'): x.payingCar(); cout<<"\rPayed"; break;
case('N'): x.nopayCar(); cout<<"\rNot payed"; break;
case(27 ): x.display(); goto end;}
}
end:
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/**3. Create a class called time that has separate int member data for hours, minutes, and seconds.
One constructor should initialize this data to 0, and another should initialize it to fixed values.
Another 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 (should they be const?) and one that isnt
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 this third variable. Make appropriate member
functions const. */
#include<iostream>
#include<conio.h>
using namespace std;

class time{
int hours, minutes, seconds;
public:
time(): hours(0), minutes(0), seconds(0) {}
time(int h, int m, int s): hours(h), minutes(m), seconds(s) {}
void display() const { cout<<hours<<":"<<minutes<<":"<<seconds;}
void add(time x, time y){
long tmp;
tmp=x.hours*3600+x.minutes*60+x.seconds+y.hours*3600+y.minutes*60+y.seconds;
seconds=tmp%60; minutes=((tmp-seconds)%3600)/60; hours=tmp/3600;
if(seconds>59) {seconds-=59; minutes++;}
if(minutes>59) {minutes-=59; hours++;}}};

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

const time t1(12, 34, 4), t2(3, 34, 45);
time t3;

do{
t3.add(t1, t2);
t3.display();
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*4. Create an employee class, basing it on Exercise 4 of Chapter 4. The member data should
comprise an int for storing the employee number, and a float for storing the employees
compensation. Member functions should allow the user to enter this data and display it. Write a main
() that allows the user to enter data for three employees and display it.*/
#include<iostream>
#include<iomanip>
#include<conio.h>
using namespace std;

class employee{
int emp_num;
float emp_comp;
public:
void assign(int en, float ec){ emp_num=en; emp_comp=ec;}
void disp() const { cout<<endl<<setw(25)<<emp_num<<setw(25)<<emp_comp;}
};

void main(void)
{
cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<"------------------------\n"<<endl;

employee x[3]; int a; float b;

do{
for(int i=0; i<3;){
cout<<"Enter the employee "<<++i<<" number : "; cin>>a;
cout<<"Enter the employee "<< i<<" compensation: "; cin>>b;
x[i-1].assign(a, b);}
cout<<setw(25)<<"employees number"<<setw(25)<<"employee's compensation";
for(int j=0; j<3; j++) { x[j].disp();}
cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
}while(getch()=='c');
}

/*5. Start with the date structure in Exercise 5 in Chapter 4 and transform it into a date class. Its
member data should consist of three ints: month, day, and year. It should also have two member
functions: getdate(), which allows the user to enter a date in 12/31/97 format, and showdate(), which
displays the date. */
#include<iostrea