Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

Sunday, November 18, 2018

Time Class and Its Implementation in C++

Leave a Comment

Time.h

#ifndef TIME_H
#define TIME_H

class Time
{
    public:
        Time();
        Time(int,int,int);
        virtual ~Time();
        Time(const Time& other);
        int Gethour() { return hour; }
        void Sethour(int val) { hour = val; }
        int Getminutes() { return minutes; }
        void Setminutes(int val) { minutes = val; }
        int Getseconds() { return seconds; }
        void Setseconds(int val) { seconds = val; }
    protected:
    private:
        int hour;
        int minutes;
        int seconds;
};
#endif // TIME_H

Time.cpp

#include "Time.h"
Time::Time()
{
    this.Sethour(0);
    this.Setminutes(0);
    this.Setseconds(0);
}
Time::Time(int hour,int minut,int sec)
{
    this.Sethour(hour);
    this.Setminutes(minut);
    this.Setseconds(sec);
}
Time::~Time()
{
    //dtor
}
Time::Time(const Time& other)
{
    //copy ctor
}


main.cpp

#include <iostream>
#include "Time.h"
using namespace std;
int main()
{
    Time myTime=new Time();
   
    cout << "Hello world!" << endl;
    return 0;
}
Read More

Saturday, January 28, 2017

Object-Oriented Programming in C++ Fourth Edition By Robert Lafore Chapter-4 C++ Structures -- Questions+Exercises

Leave a Comment

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.

Answer: b,d

2. True or false: A structure and a class use similar syntax.

Answer: true

3. The closing brace of a structure is followed by a __________.

Answer: semicolon

4. Write a structure specification that includes three variables—all of type int—called hrs, mins, and secs. Call this structure time.

Answer: 
struct time
{
int hrs;
int mins;
int secs;

};

5. True or false: A structure definition creates space in memory for a variable.

Answer:false; only a variable definition creates space in memory

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.

Answer:c

7. Write a statement that sets the hrs member of the time2 structure variable equal to 11.

Answer:time2.hrs = 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?

Answer:18 in 16-bit systems (3 structures times 3 integers times 2 bytes), or 36 in 32-bit systems

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.

Answer:time time1 = { 11, 10, 59 };

10. True or false: You can assign one structure variable to another, provided they are of the same type.

Answer:true

11. Write a statement that sets the variable temp equal to the paw member of the dogs mem-ber of the fido variable.

Answer:temp = fido.dogs.paw;

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.

Answer:c

13. Write a statement that declares an enumeration called players with the values B1, B2, SS, B3, RF, CF, LF, P, and C.

Answer:enum players { B1, B2, SS, B3, RF, CF, LF, P, 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.

Answer:players joe, tom;
joe = LF;
tom = P;

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;

Answer:
a. no
b. yes
c. no

d. yes

16. The first three enumerators of an enum type are normally represented by the values _________, _________, and _________.

Answer:0, 1, 2

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.

Answer:enum speeds { obsolete=78, single=45, album=33 };

18. State the reason that enum isWord{ NO, YES }; is better than enum isWord{ YES, NO };

Answer:because false should be represented by 0


Exercises

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

Enter your area code, exchange, and number: 415 555 1212
My number is (212) 767-8900
Your number is (415) 555-1212

Solution: Question 1

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

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

Solution: Question 2

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

Solution: Question 3

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.

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.

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.

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

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

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

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

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

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.



Note :: All credit and all rights belong to Robert Lafore and their respective partners. I do not own this material, nor do i claim to do so. This material is only for educational purpose.

Read More

Friday, January 6, 2017

Create the equivalent of a four-function calculator. The program should ask 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 whether 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

Leave a Comment
Object-Oriented Programming in C++ Fourth Edition By Robert Lafore Chapter-3 C++ Loops and Decisions  -- Questions+Exercises

Question:

Create the equivalent of a four-function calculator. The program should ask 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 whether 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

Explanation:
Below mention code is compiled in Visual Studio 2015 and Code Blocks 13.12,output snap is attached.. If any problem you feel and you want some explanation feel free to contact us.

Code:

/**************************************************|
/*************C++ Programs And Projects************|
***************************************************/
#include <iostream>
using namespace std;
int main()
{
       double n1, n2, ans;
       char oper, ch;
       do {
              cout << "\nEnter first number, operator, second number : ";
              cin >> n1 >> oper >> n2;
              switch (oper)
              {
              case '+':  ans = n1 + n2;  break;
              case '-':  ans = n1 - n2;  break;
              case '*':  ans = n1 * n2;  break;
              case '/':  ans = n1 / n2;  break;
              default:   ans = 0;
              }
              cout << "Answer = " << ans;
              cout << "\nDo another(Enter ‘y’ or ‘n’) ? ";
              cin >> ch;
       } while (ch != 'n');
       return 0;

}

Output:
Create the equivalent of a four-function calculator. The program should ask 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 whether 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



Related Articles:



Read More

Thursday, January 5, 2017

Object-Oriented Programming in C++ Fourth Edition By Robert Lafore Chapter-2 C++ Programming Basics -- Questions+Exercises

Leave a Comment

Object-Oriented Programming in C++ Fourth Edition By Robert Lafore Chapter-2 C++ Programming Basics -- Questions+Exercises

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.

Answer: b,c

2. A function name must be followed by ________.

Answer: parentheses

3. A function body is delimited by ________.

Answer: braces { }

4. Why is the main() function special?

Answer: It’s the first function executed when the program starts

5. A C++ instruction that tells the computer to do something is called a ________.

Answer: statement

6. Write an example of a normal C++ comment and an example of an old-fashioned /* comment.

Answer: 

// this is a comment

/* this is a 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.

Answer:a, d

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

Answer: 

a. 4
b. 10
c. 4
d. 4

9. True or false: A variable of type char can hold the value 301.

Answer: false

10. What kind of program elements are the following?
            a. 12
            b.‘a’
            c. 4.28915
            d. JungleJim
            e. JungleJim()

Answer: 

a. integer constant
b. character constant
c. floating-point constant
d. variable name or identifier

e. function name

11. Write statements that display on the screen
            a. the character ‘x’
            b. the name Jim
            c. the number 509

Answer:

a.cout << ‘x’;
b. cout << “Jim”;

c. cout << 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.

Answer: false; they’re not equal until the statement is executed

13. Write a statement that displays the variable george in a field 10 characters wide.

Answer: cout << setw(10) << george;

14. What header file must you #include with your source file to use cout and cin?

Answer: IOSTREAM

15. Write a statement that gets a numerical value from the keyboard and places it in the variable temp.

Answer: cin>>temp

16. What header file must you #include with your program to use setw?

Answer: iomanip

17. Two exceptions to the rule that the compiler ignores whitespace are ________ and
________.

Answer: string constants, preprocessor directives

18. True or false: It’s perfectly all right to use variables of different data types in the same arithmetic expression.

Answer: true

19. The expression 11%3 evaluates to ________.

Answer: 2

20. An arithmetic assignment operator combines the effect of what two operators?

Answer: assignment (=) and arithmetic (like + and *)

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.

Answer: 

temp += 23;

temp = temp + 23;

22. The increment operator increases the value of a variable by how much?

Answer: 1

23. Assuming var1 starts with the value 20, what will the following code fragment print out?
            cout << var1--;
            cout << ++var1;

Answer: 2020

24. In the examples we’ve seen so far, header files have been used for what purpose?

Answer: to provide declarations and other data for library functions, overloaded operators,and
objects

25. The actual code for library functions is contained in a ________ file.

Answer: library

Exercises

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.

Solution: Question 1

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.

Solution: Question 2

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 decrements operator to generate the 19.

Solution: Question 3

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.

Solution: Question 4

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.)

Solution: Question 5

6. On a certain day the British pound was equivalent to $1.487 U.S., the French franc was $0.172, the German deutsche mark 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.

Solution: Question 6

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.

Solution: Question 7

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 Port City.....2425785

Solution: Question 8

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;

Solution: Question 9

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 most compilers you can use the decimal number 156 (hex character constant ‘\x9c’) to represent the pound sign (£). In some compilers, you can put the pound sign into your program directly by pasting it from the Windows Character Map accessory. 

Solution: Question 10

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

Solution: Question 11

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.

Solution: Question 12


Note :: All credit and all rights belong to Robert Lafore and their respective partners. I do not own this material, nor do i claim to do so. This material is only for educational purpose. 


Read More

Tuesday, December 13, 2016

Object-Oriented Programming in C++ Fourth Edition By Robert Lafore Chapter-1 The Big Picture -- Questions

Leave a Comment
1. Pascal, BASIC, and C are p_____ languages, while C++ is an o_____ language.

Answer: procedural, object-oriented

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.

Answer: b

3. The two major components of an object are_____ and functions that _____.

Answer: data, act on that data

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.

Answer: a

5. Protecting data from access by unauthorized functions is called _____.

Answer: data hiding

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.

Answer: a and d

7._____ model entities in the real world more closely than do functions.

Answer: objects

8. True or false: A C++ program is similar to a C program except for the details of coding.

Answer: false; the organizational principles are different

9. Bundling data and functions together is called_____.

Answer: encapsulation

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.

Answer: d

11. True or false: You can easily tell, from any two lines of code, whether a program is written in C or C++.

Answer: false; most lines of the code are same in c and c++

12. The ability of a function or operator to act in different ways on different data types is called __________.

Answer: polymorphism

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.

Answer: d

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.

Answer: b

15. The Unified Modeling Language is
               a. a program that builds physical models.
               b. a way to look at the organization of a program.
               c. the combination of C++ and FORTRAN.
               d. helpful in developing software systems.

Answer: b and d






Note :: All credit and all rights belong to Robert Lafore and their respective partners. I do not own this material, nor do i claim to do so. This material is only for educational purpose. 


Read More