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


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Page 1 of 2 12 LastLast
Results 1 to 15 of 27

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

  1. #1
    Join Date
    Oct 2005
    Location
    Maady
    Posts
    1,819

    Arrow 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.
    >>>>>>>>>>>>>>>>>>>>>
    Programmer&Cracker CS
    MyBlog:Blog.Amahdy.com
    MyWebsite:www.Amahdy.com

  2. #2
    Join Date
    Oct 2005
    Location
    Maady
    Posts
    1,819
    CHAPTER 1—THE 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. It’s 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
    ________
    Programmer&Cracker CS
    MyBlog:Blog.Amahdy.com
    MyWebsite:www.Amahdy.com

  3. #3
    Join Date
    Oct 2005
    Location
    Maady
    Posts
    1,819
    CHAPTER 2—C++ 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: It’s 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 we’ve 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. It’s 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; they’re 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
    ________
    Programmer&Cracker CS
    MyBlog:Blog.Amahdy.com
    MyWebsite:www.Amahdy.com

  4. #4
    Join Date
    Oct 2005
    Location
    Maady
    Posts
    1,819

    Arrow

    CHAPTER 2—C++ PROGRAMMING BASICS codes;


    Code:
    /**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');
    }
    Code:
    /**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');
    }
    Code:
    /**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');
    }
    Code:
    /*4.  Write a program that displays your favorite poem. Use an appropriate escape sequence for the
      line breaks. If you don’t 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');
    }
    Code:
    /*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');
    }
    Code:
    /*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');
    }
    Programmer&Cracker CS
    MyBlog:Blog.Amahdy.com
    MyWebsite:www.Amahdy.com

  5. #5
    Join Date
    Oct 2005
    Location
    Maady
    Posts
    1,819

    Arrow

    Code:
    /*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');
    }
    Code:
    /*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 &ltiostream>
    !#include &ltiomanip>     // 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');
    }
    Code:
    /*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 don’t 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');
    }
    Programmer&Cracker CS
    MyBlog:Blog.Amahdy.com
    MyWebsite:www.Amahdy.com

  6. #6
    Join Date
    Oct 2005
    Location
    Maady
    Posts
    1,819

    Arrow

    Code:
    /*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). We’ll 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 user’s 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');
    }
    Code:
    /*11.  By default, output is right-justified in its field. You can left-justify text output using the
      manipulator setiosflags(ios::left). (For now, don’t 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
          O’Brian    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');
    }
    Code:
    /*12.  Write the inverse of Exercise 10, so that the user enters an amount in Great Britain’s 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');
    }
    Programmer&Cracker CS
    MyBlog:Blog.Amahdy.com
    MyWebsite:www.Amahdy.com

  7. #7
    Join Date
    Oct 2005
    Location
    Maady
    Posts
    1,819
    CHAPTER 3—LOOPS 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
    ________
    Programmer&Cracker CS
    MyBlog:Blog.Amahdy.com
    MyWebsite:www.Amahdy.com

  8. #8
    Join Date
    Oct 2005
    Location
    Maady
    Posts
    1,819
    CHAPTER 3—LOOPS AND DECISIONS codes;


    Code:
    /**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');
    }
    Code:
    /**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 that’s 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');
    }
    Code:
    /**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.) 
      Here’s 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');
    }
    Code:
    /**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();}
    }
    Code:
    /*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');
    }
    Programmer&Cracker CS
    MyBlog:Blog.Amahdy.com
    MyWebsite:www.Amahdy.com

  9. #9
    Join Date
    Oct 2005
    Location
    Maady
    Posts
    1,819
    Code:
    /*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);
    }
    Code:
    /*7.  Write a program that calculates how much money you’ll 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');
    }
    Code:
    /*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, you’ll 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');
    }
    Code:
    /*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.) Don’t 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');
    }
    Code:
    /*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? (Don’t 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');
    }
    Programmer&Cracker CS
    MyBlog:Blog.Amahdy.com
    MyWebsite:www.Amahdy.com

  10. #10
    Join Date
    Oct 2005
    Location
    Maady
    Posts
    1,819
    Code:
    /*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 doesn’t make sense to multiply two money amounts; there is no such thing
      as square money. We’ll 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;}
    }
    Code:
    /*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');
    }
    Programmer&Cracker CS
    MyBlog:Blog.Amahdy.com
    MyWebsite:www.Amahdy.com

  11. #11
    Join Date
    Oct 2005
    Location
    Maady
    Posts
    1,819
    CHAPTER 4—STRUCTURES


    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 variables—all of type int—called 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 time1—which is a variable of type struct time, as defined in Question 4—to 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.
    ________
    Programmer&Cracker CS
    MyBlog:Blog.Amahdy.com
    MyWebsite:www.Amahdy.com

  12. #12
    Join Date
    Oct 2005
    Location
    Maady
    Posts
    1,819
    CHAPTER 4—STRUCTURES codes;


    Code:
    /**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');
    }
    Code:
    /**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');
    }
    Code:
    /**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');
    }
    Code:
    /*4.  Create a structure called employee that contains two members: an employee number (type int)
      and the employee’s compensation (in dollars; type float). Ask the user to fill in this data for three
      employees, store it in three variables of type struct employee, and then display the information for
      each employee.*/
    #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');
    }
    Code:
    /*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');
    }
    Programmer&Cracker CS
    MyBlog:Blog.Amahdy.com
    MyWebsite:www.Amahdy.com

  13. #13
    Join Date
    Oct 2005
    Location
    Maady
    Posts
    1,819
    Code:
    /*6.  We said earlier that C++ I/O statements don’t automatically understand the data types of
      enumerations. Instead, the (>>) and (<<) operators think of such variables simply as integers. You
      can overcome this limitation by using switch statements to translate between the user’s way of
      expressing an enumerated variable and the actual values of the enumerated variable. For example,
      imagine an enumerated type with values that indicate an employee type within an organization:
      
      enum etype { laborer, secretary, manager, accountant, executive,
      researcher };
    
    
      Write a program that first allows the user to specify a type by entering its first letter (‘l’, ‘s’, ‘m’, and
      so on), then stores the type chosen as a value of a variable of type enum etype, and finally displays
      the complete word for this type.
      
      Enter employee type (first letter only)
         laborer, secretary, manager,
         accountant, executive, researcher): a
      Employee type is accountant.
    
    
    
      You’ll probably need two switch statements: one for input and one for output.*/
    #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');
    }
    Code:
    /*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 employee’s
      compensation, the employee type, and the date of first employment. The program should store this
      information in three variables of type employee, and then display their contents.*/
    #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');
    }
    Code:
    /*8.  Start with the fraction—adding program of Exercise 9 in Chapter 2, “C++ Programming Basics.”
      This program stores the numerator and denominator of two fractions before adding them, and may
      also store the answer, which is also a fraction. Modify the program so that all fractions are stored in
      variables of type struct fraction, whose two members are the fraction’s numerator and denominator
      (both type int). All 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');
    }
    Code:
    /*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');
    }
    Code:
    /*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');
    }
    Programmer&Cracker CS
    MyBlog:Blog.Amahdy.com
    MyWebsite:www.Amahdy.com

  14. #14
    Join Date
    Oct 2005
    Location
    Maady
    Posts
    1,819
    Code:
    /*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');
    }
    Code:
    /*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');
    }
    Programmer&Cracker CS
    MyBlog:Blog.Amahdy.com
    MyWebsite:www.Amahdy.com

  15. #15
    Join Date
    Oct 2005
    Location
    Maady
    Posts
    1,819
    CHAPTER 5—FUNCTIONS


    Questions:
    ----------
    1. A function’s 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 program’s 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 function’s return type specified?
    16. A function that doesn’t return anything has return type _________.
    17. Here’s 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 argument’s value.
    b. the function cannot access the argument’s value.
    c. a temporary variable is created in the calling program to hold the argument’s value.
    d. the function accesses the argument’s 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 argument’s 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.
    ________
    Programmer&Cracker CS
    MyBlog:Blog.Amahdy.com
    MyWebsite:www.Amahdy.com

Similar Threads

  1. Replies: 4
    Last Post: 06-03-2009, 10:08 AM
  2. Stored procedures and object oriented programming..
    By ashish Hosalkar in forum Database
    Replies: 1
    Last Post: 03-17-2000, 09:09 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center