Monday, 1 May 2017

Calculate the factorial in C++ || C++ Sample Programs

Leave a Comment
Question::

Write a program that asks the user to enter an integer number. The main() program will pass this number to a function called “ fact()”. This function will return the factorial of the input value. Show the calculated factorial of the given number on the screen.

Code:

/**************************************************|
/*************C++ Programs And Projects************|
***************************************************/
#include<iostream>
using namespace std;

int fact(int); // prototype of a function

void main() {
       int number;
       cout << "Enter a Number to find its factorial == ";
       cin >> number;
       cout<<"Factorial of "<<number<<"is == "<<fact(number);
}


//Body of a function

//Logic of factorial is pretty simple that is if we have a number like 5 then the formula of factorial
//will be like this 5*4*3*2*1
int fact(int myFactorial) {
       int result = 1;
       for (int i = 1; i <=myFactorial; i++)
       {
              if (result == 1) {
                     result = result*i;
              }
              else
              {
                     result = result*i;
              }
       }
       return result;
}




Related Articles:

C++ Primer Plus Sixth Edition Complete Solution Manual 

C++ Books Solution

  

Read More

Friday, 7 April 2017

A constructor can be virtual ?

Leave a Comment
Q 1 - A constructor can be virtual.

A - True

B - False

Answer : B

Explanation

The purpose of the constructor cannot be overridden in the derived class hence constructor cannot be a virtual.
Read More

Saturday, 18 March 2017

Control Structure in C++

Leave a Comment

The Definitive Guide To Control Structures in C++

A C++ program is not always limited to a linear sequence of instructions. A program may repeat or leaves some of its statements. 
The Control structure is a statement used to control the flow of execution in a program. These control structures are very helpful in implementing the program logic.
There are 4 types of control structures are as follows:

Sequence:

In sequential structure, the statements are executed in the same order in which they are specified in the program. The control flows from one statement to another in a logical sequence. We can write as many statements as we want but all statements are executed exactly once. It means that no statement is skipped and no statement is repeated.
For example, we want to write a program to add two numbers. The set of statements will be:
1.    Get 1st number from user.
2.    Get 2nd number from user.
3.    Sum both numbers using addition ( + ) operator.
4.    Print the sum on screen.
All these statements are written and executed only once. And the program executes them sequentially to  find sum.

Selection:

A selection structure selects a statement or set of statements to execute on the basis of a condition. In this structure, statement or set of statements is executed when a particular condition is true and ignored when the condition is false. There are different types of selection structures in C++ like:
·         IF Statement
·         IF...ELSE Statement
·         SWITCH Statement

The IF statement is a single-selection statement because it selects or ignores a single action. The IF...ELSE statement is called a double-selection statement because it selects between two different actions (or groups of actions). The SWITCH selection statement is called a multiple-selection statement because it selects among many different actions.

For example, we want to write a program which checks whether the number entered by user is eve or odd. The program will print even if it is an even number and program will print Odd if it is an odd number. The set of statements will be:
1.    Get the number from user.
2.    Check whether it is even or odd.
3.    Print Even if it was an even number.
4.    Print Odd  if it was an odd number.
In above example, statement no. 2 is used to make a decision. On the base of this decision, statement no. 3 or 4 is executed by computer. If your want complete source code then Click Here.

Repetition:

A repetition structure executes a statement or set of statements repeatedly. It is also known as iteration structure  or loop.
This structure is also based on conditions. Statements are repeated as long as a condition remains true.
There are 3 different types of repetition structures in C++ like:
·         WHILE Loop
·         DO...WHILE Loop
·         FOR Loop

The WHILE and FOR statements perform the action in their bodies zero or more times. If the loop-continuation condition is initially false, the loop body will not be executed. The DO...WHILE statement performs the action in its body at least once.

For example, we want to print “Hello World” 500 times on the screen. If we accomplish this job using sequence structure then we would write 500 lines of code which is very time consuming. We can do this by using just a single statement of repetition structure. An example of this structure can be found Here.  

Function Call:

Function call is a type of statement that moves the control to another block of code. The control returns back after executing all statements in the block. The remaining statements are executed immediately after the function call when the control is returned.


About Author:

Kamal Choudhary is a tech geek who loves to write about technology and programming. His personal blog contains some cutting-edge C++ Programming Tutorials. He is studying Computer Science in University of Gujrat, Pakistan.



Read More

Saturday, 28 January 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.
Read More

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

Leave a Comment

Question:

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.


Explanation:

We strongly recommend you to minimize your browser and try this yourself first.


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************|
***************************************************/
// uses structure to model volume of room
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
struct Distance
{
       int feet;
       float inches;
};
////////////////////////////////////////////////////////////////
struct Volume
{
       Distance length;
       Distance width;
       Distance height;
};
////////////////////////////////////////////////////////////////
int main()
{
       float l, w, h;
       Volume room1 = { { 16, 3.5 },{ 12, 6.25 },{ 8, 1.75 } };
       l = room1.length.feet + room1.length.inches / 12.0;
       w = room1.width.feet + room1.width.inches / 12.0;
       h = room1.height.feet + room1.height.inches / 12.0;
       cout << "Volume = " << l*w*h << " cubic feet\n";
       return 0;

}

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



Related Articles:



Read More

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

Leave a Comment

Question:

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

Explanation:

We strongly recommend you to minimize your browser and try this yourself first.

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************|
***************************************************/
// structure models point on the plane
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
struct point
{
       int xCo;     //X coordinate
       int yCo;     //Y coordinate
};
////////////////////////////////////////////////////////////////
int main()
{
       point p1, p2, p3;                        //define 3 points
       cout << "\nEnter coordinates for p1: "//get 2 points
       cin >> p1.xCo >> p1.yCo;                 //from user
       cout << "Enter coordinates for p2: ";
       cin >> p2.xCo >> p2.yCo;
       p3.xCo = p1.xCo + p2.xCo;                //find sum of
       p3.yCo = p1.yCo + p2.yCo;                //p1 and p2
       cout << "Coordinates of p1 + p2 are : "     //display the sum
              << p3.xCo << ", " << p3.yCo << endl;
       return 0;

}

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



Related Articles:



Read More

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

Leave a Comment

Question:

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

Explanation:

We strongly recommend you to minimize your browser and try this yourself first.


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************|
***************************************************/
// uses structure to store phone number
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
struct phone
{
       int area;         //area code (3 digits)
       int exchange;     //exchange (3 digits)
       int number;       //number (4 digits)
};
////////////////////////////////////////////////////////////////
int main()
{
       phone ph1 = { 212, 767, 8900 };  //initialize phone number
       phone ph2;                       //define phone number
                                                               // get phone no from user
       cout << "\nEnter your area code, exchange, and number";
       cout << "\n(Don’t use leading zeros) : ";
       cin >> ph2.area >> ph2.exchange >> ph2.number;
       cout << "\nMy number is "        //display numbers
              << '(' << ph1.area << ") "
              << ph1.exchange << ' - ' << ph1.number;
       cout << "\nYour number is "
              << '(' << ph2.area << ") "
              << ph2.exchange << ' - ' << ph2.number << endl;
       return 0;
}

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



Related Articles:


Read More