Exercise 1
1. Design an algorithm in flowchart to find the smallest number in a group of three real numbers.
2. Design an algorithm in flowchart to solve the quadratic equation: ax^2 + bx + c =0 with the inputs a, b, and c.
3. A set of linear equations:
aX + bY = c
dX + eY = f
can be solved using Cramer’s rule as:
X = (ce – bf)/(ae – bd)
Y = (af – cd)/(ae – bd)
Design an algorithm in flowchart to read in a, b, c, d, e and f and then solve for X and Y.
4. Design an algorithm in flowchart to read in a group of N numbers and compute the average of them, where N is also an input.
5. Design an algorithm in flowchart to read in a group of N numbers and compute the sum of them, where N is also an input.
Exercise 2
1. Read the following C++ program for understanding. Add some suitable declarations to complete the program and run it.
#<include<iostream.h>
void main(){
...
units = 5;
price = 12.5;
idnumber = 12583;
cost = price*units;
cout << idnumber << “ “ << units << “ “ << price << “ “ << cost << endl;
tax = cost*0.06;
total = cost + tax;
cout << tax << “ “ << total << endl;
}
2. Write and run a program to print your first name on the first line, your middle name on the second line and your last name on the third line using only cout statement.
3. Write and run a program that performs the following steps:
- Assigning value to the radius r.
- Calculating the circumference using the formula: C = 2*pi*r.
- Displaying the circumference.
4. Given an initial deposit of money, denoted as P, in a bank that pays interest annually, the amount of money at a time N years later is given by the formula:
Amount = P*(1 + R)^N
where R is the interest rate as a decimal number (e.g., 6.5% is 0.065). Using this formula, design, write and run a program that determines the amount of money that will be available in 4 years if $10.000 is deposited in a bank that pays 7% interest annually.
5. Write and run a program that performs the following steps:
- Assigning value to a Fahrenheit temperature f.
- Calculating the equivalent Celsius temperature C using the formula:
C = (5/9)(f –32).
- Displaying the Celsius temperature C.
Exercise 3
1. Write and run a program that performs the following steps:
- Reading the radius r from the keyboard.
- Calculating the circumference using the formula: C = 2*pi*r.
- Displaying the circumference C.
2. Write and run a program that performs the following steps:
- Reading a Fahrenheit temperature f from the keyboard.
- Calculating the equivalent Celsius temperature C using the formula:
C = (5/9)(f –32).
- Displaying the Celsius temperature C.
3. Write and run a program that reads two integers through the keyboard and performs simple arithmetic operations (i.e., addition, subtraction, multiplication and division) and displays the results.
4. Write and run a program that reads a floating-point number through the keyboard and performs its square root and displays the result with 4 digits of precision to the right of the decimal point.
5. Given an initial deposit of money, denoted as P, in a bank that pays interest annually, the amount of money at a time N years later is given by the formula:
Amount = P*(1 + R)^N
where R is the interest rate as a decimal number (e.g., 6.5% is 0.065). Write and run a program that performs the following steps:
- Reading the values of P and R from the keyboard.
- Calculating the amount of money that will be available in 5 years.
- Displaying the result.
6. Write and run a program that reads the name, age, sex, height and weight of a student and displays with proper heading for each variable.
7. Write a program to accept a single character from the keyboard. Using cout statement to display the character or keystroke and its decimal, hexadecimal and octal values. Display in the following format:
Exercise 4
1. Write and run a program that reads a character and writes out a name corresponding to the character:
if the character is ‘F’ or ‘f’ then the name is ‘Frank’
if the character is ‘C’ or ‘c’ then the name is ‘Christine’
if the character is ‘A’ or ‘a’ then the name is ‘Amanda’
if the character is ‘B’ or ‘b’ then the name is ‘Bernard’
otherwise, the name is just the character.
2. Write and run a program that reads an angle (expressed in degrees) and states in which quadrant the given angle lies. An angle A is said to be in the
- first quadrant if it is in the range 0 <= A < 90
- second quadrant if it is in the range 90 <= A < 180
- third quadrant if it is in the range 180 <= A < 270
- and fourth quadrant if it is in the range 270 <= A < 360.
3. Write and run a program that reads a month from the user and displays the number of days in that month.
4. Write and run a program that reads a numeric grade from a student and displays a corresponding character grade for that numeric grade. The program prints ‘A’ for exam grades greater than or equal to 90, ‘B’ for grades in the range 80 to 89, ‘C’ for grades in the range 70 to 79, ‘D’ for grades in the range 60 to 69 and ‘F’ for all other grades.
5. Write and run a program that reads a marriage code (one character) and writes out a message corresponding to the character:
if the character is ‘M’ or ‘m’ then the message is “Individual is married”
if the character is ‘D’ or ‘d’ then the message is “Individual is divorced”
if the character is ‘W’ or ‘w’ then the message is “Individual is widowed”
otherwise, the message is “An invalid code was entered”.
(Hint: use switch statement).
6. Chapter 4 contains the example program which can solve quadratic equations. Modify that program so that when the discriminant del is negative, the imaginary roots are calculated and displayed. For this case, the two roots of the equation are:
x1 = (-b)/(2a) + sqrt(-del)/(2a)i
x2 = (-b)/(2a) + sqrt(-del)/(2a)i
where i is the imaginary number symbol for the square root of –1. (Hint: Calculate the real and imaginary parts of each root separately).
7. Write and run a program that gives the user only three choices: convert from Fahrenheit to Celsius, convert from Celsius to Fahrenheit, or quit. If the third choice is selected, the program stops. If one of the first two choices is selected, the program should prompt the user for either a Fahrenheit or Celsius temperature, as appropriate, and then compute and display a corresponding temperature. Use the conversion formulas:
F = (9/5)C + 32
C = (5/9)(F-32)
8. Write a C++ program to calculate the square root and the reciprocal of a user-entered number. Before calculating the square root, you should validate that the number is not negative, and before calculating the reciprocal, check that the number is not zero.
Exercise 5
1. Write and run a program that reads a positive integer value for K and then computes K! = 1*2*3*…*(K-1)*K and displays the result out.
2. Write and run a program that computes x raised to the power n by repetitive multiplication. Then modify your program to calculate x raised to the power (-n).
3. Write and run a program to tabulate sin(x), cos(x) and tan(x) for x = 5, 10, 15,…,85 degrees. Notice that you have to convert x from degrees to radians before using standard functions sin(x), cos(x), tan(x).
4. Write and run a program to read a list of real numbers and then find the number of positive values and the number of negative ones among them. The number of entries is also entered by the user.
5. Write and run a program to compute the sum of square of the integers from 1 to N, where N is an input parameter.
6. Write and run a program to compute the value of pi, using the series for approximating:
pi/4 = 1-1/3+1/5-1/7+ ... + (-1)^n/(2*n+1)
Hint: Use a while loop that terminates when the difference between two successive approximations is less than 1.0E-6.
7. The value of Euler’s number, e, can be approximated using the formula:
e = 1 + 1/1! +1/2! + 1/3! +1/4! + … +1/n!
Using this formula, write a program that approximates the value of e using a while loop that terminates when the difference between two successive approximations is less than 1.0E-6.
8. The Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, 13,…, where the first two terms are 0 and 1, and each term thereafter is the sum of the two preceding terms, that is, Fib(n) = Fib(n-1) + Fib(n-2). Using this information, write a program that calculates the nth number in a Fibonacci sequence, where n is entered into the program by the user.
9. Write and run a program that inputs an array of N real numbers, and then computes the average value of the array elements. N should be an input parameter.
10. Write and run a program that inputs an array of N real numbers, and then finds the largest element in the array. N should be an input parameter.
11. Write and run a program that inputs an integer matrix of order n and transposes it and then prints it out. Transposing a square matrix means:
a(i,j) <==> a(j,i) for all i, j.
12. The Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, 13,…, where the first two terms are 0 and 1, and each term thereafter is the sum of the two preceding terms. Write a program that computes and stores the Fibonacci sequence in an integer array F, such that F[i] will store the ith number in a Fibonacci sequence. The size of the array is an input parameter which is entered by the user.
13. Write a program that stores the following hourly rates in an array name hourly_rates: 9.5, 6.4, 12.5, 5.5, 10.5. Your program should also create two arrays named working_hours and wages, each capaple of storing five double-precision numbers. Using a for loop and a cin statement, have your program accept five user-input numbers into working_hours array when the program is run. Your program should store the product of the corresponding values in the hourly_rates and working_hours arrays in the wages array (for example, wages[1] = hourly_rate[1]*working_hours[1]) and display the output as a table consisting of three columns.
14. Write and run a program that reads three strings and prints them out in an alphabetical order. (Hint: Use the strcmp() function).
15. Modify the program in Section Array of Structures to compute and display the average rate of the five first employees.
16. The following program reads a set of name, roll number, sex, height and weight of the students from the keyboard using a structure within an array.
#include<iostream.h>
#include<string.h>
const int MAX = 100
struct student{
char name[20];
long int rollno;
char sex;
float height;
float weight;
};
void main(){
student cls[MAX];
int i,n;
cout << “ How many names ? \n“;
cin >> n;
for( i = 0; i <= n-1; ++i){
cout << “record = “<< i+1 << endl;
cout << “name : “; cin>> cls[i].name;
cout << “rollno : “; cin>> cls[i].rollno;
cout << “sex : “; cin>> cls[i].sex;
cout << “height : “; cin>> cls[i].height;
cout << “weight : “; cin>> cls[i].weight;
cout >> endl;
}
……
}
Include into the above program the code that performs two tasks:
a. displaying data of n students in the following format:
b. computing and displaying the average of heights and the average of weights of the students.
Exercise 6
1. a. Write a function inorder that determines whether the three characters are in alphabetic order or not. It returns true if the three arguments are in order or false otherwise.
b. Write a complete program that reads three characters and calls the function inorder to report whether they are in alphabetic order, loops until reading “***”.
2. a. Write a function IntSquare that computes the greatest integer so that its square is less than or equal to a given number.
b. Write a complete program that reads an integer n and invokes the function IntSquare to compute the greatest integer so that its square is less than or equal to n.
3. a. Write a function that computes the fourth root of its integer argument k. The value returned should be a double. (Hint: Use the library function sqrt()).
b. Write a complete program that reads an integer n and invokes the function to compute the fourth root of n.
4. a. Write a function is_prime(n) that returns true if n is a prime or false, otherwise.
b. Write a complete program that reads an integer n and invokes the function to check whether n is prime.
5. We can recursively define the number of combinations of m things out of n, denote C(n, m), for n >= 1 and 0 <= m <= n, by
C(n,m) = 1 if m = 0 or m=n
C(n, m) = C(n-1, m) + C(n-1, m-1) if 0 < m < n
- Write a recursive function to compute C(n, m).
- Write a complete program that reads two integers N and M and invokes the function to compute C(N, M) and prints the result out.
6. Given a function as follows:
int cube(int a)
{
a = a*a*a;
return a;
}
- Write a complete program that reads an integer n and invokes the function to compute its cube.
- Rewrite the function so that the parameter is passed by reference. It is named by cube2. Write a complete program that reads an integer n and invokes the function cube2 to compute its cube, prints the result out and then displays the value of n. What is the value of n after the function call?
7. a. Write a function that can find the largest element in the array that is passed to the function as a parameter.
b. Write a program that inputs an array and invokes the above function to find the largest element in the array and print it out.
8. Given the following function that can find a specified value in an array. If the search is successful, this function returns the position of the specified value in the array, otherwise, it returns –1.
int linearSearch(int array[], int key, int sizeofArray)
{
for(int n = 0; n< sizeofArray; n++)
if (array[n] = = key)
return n;
return –1;
}
Write a program that performs the following steps:
- Input the integer array of N elements. (N is also an input data).
- Input a value you want to search on the array.
- Invoke the function linearSearch to find the element in the array which is equal to the specified value(assume that position is k).
- Remove that element at location k from the array.
9. A palindrome is a string that reads the same both forward and backward. Some examples are
Given the following function that returns true if the parameter string is a palindrome or false, otherwise.
bool palindrome(char strg[])
{
int len, k, j;
len = strlen(strg);
k = len/2;
j = 0;
bool palin = true;
while ( j < k && palin)
if (strg[j] != strg[len -1-j])
palin = false;
else
++ j;
return (palin)
}
Write a C++ program that reads several strings, one at a time and checks if each string is a palindrome or not. Use a while loop in your program. The loop terminates when the user enters a string starting with a ‘*’.
10. Given the following program:
#include<iostream.h>
int main()
{
const int NUMS = 5;
int nums[NUMS] = {16, 54, 7, 43, -5}
int i, total = 0;
int *nPt;
nPt = nums;
for( i = 0; i<NUMS; i++)
total = total + *nPt++;
cout << total<< endl;
return 0;
}
a. Explain the meaning of the program.
b. Run to determine the result of the program.
11. Given the following function that can find the largest element in an integer array. Notice that the function uses pointer arithmetic:
int findMax(int * vals, int numEls)
{
int j, max = *vals;
for (j = 1; j < numEls; j++)
if (max < *(vals + j))
max = *(vals + j);
return max;
}
Write a C++ program that inputs an integer array and invokes the above function to find the largest element in that array and displays the result out.
12. a. Write a function named days() that determines the number of days from the date 1/1/1900 for any date passed as a structure. Use the Date structure:
struct Date
{
int month;
int day;
int year;
}
In writing the days() function, use the convention that all years have 360 days and each month consists of 30 days. The function should return the number of days for any Date structure passed to it.
b. Rewrite the days() function to receive a pointer to a Date structure rather than a copy of the complete structure.
c. Include the function written in b) in a complete C++ program.
Exercise 7
1. Given the class student which is defined as follows:
class student{
private:
long int rollno;
int age;
char sex;
float height;
float weight;
public:
void getinfo();
void disinfo();
};
void student::getinfo()
{
cout << " Roll no :";
cin >> rollno;
cout << " Age :";
cin >> age;
cout << " Sex:";
cin >> sex;
cout << " Height :";
cin >> height;
cout << " Weight :";
cin >> weight;
}
void student::disinfo()
{
cout<<endl;
cout<< " Roll no = "<< rollno << endl;
cout<< " Age =" << age << endl;
cout<< " Sex =" << sex << endl;
cout<< " Height =" << height << endl;
cout<< " Weight =" << weight << endl;
}
Write the main program that creates an array of student objects, accepts the data of n students and displays the data of all elements in this array. The value of n is also entered by the user.
Remember to organize the program into one interface file and one implementation file and run them again.
2. Construct a class named Account consisting of four private data members: name of the customer, account number, balance and rate. The public member functions include a constructor and five other member functions that are listed as follows.
- to make a deposit
- to withdraw an amount from the balance
- to get the rate of interest
- to know the balance amount
Include the class Account within a complete program. The program should declare two objects of type Account and accept and display data for the objects to verify the operation of the member functions.
3. Given the class equation which is defined as follows:
class equation{
private:
float a;
float b;
float c;
public:
void getinfo(float a, float b, float c);
void display( );
void equal(float a, float b);
void imag( );
void real(float a, float b, float det);
}; // end of class declaration section
// beginning of implementation section
void equation::getinfo(float aa, float bb, float cc)
{
a = aa; b = bb; c = cc;
}
void equation::display( )
{
cout << endl;
cout << “ a = “<< a << “\t”;
cout << “ b = “ << b << “\t”;
cout << “ c = “ << c << endl;
}
void equation::equal(float a, float b)
{
float x;
x = -b/(2*a);
cout << “ roots are equal = “<< x << endl;
}
void equation::imag(){
cout << “ roots are imaginary \n”;
}
void equation::real(float a, float b, float det)
{
float x1, x2, temp;
tem = sqrt(det);
x1 = (-b+temp)/(2*a); x2 = (-b-temp)/(2*a);
cout << “ roots are real \n”;
cout << “ x1 = “ << x1 << endl;
cout << “ x2 = “ << x2 << endl;
}
Write a main program that accepts the coefficients of a given quadratic equation and makes use of the member functions of the class equation to solve the equation.
Remember to organize the program into one interface file and one implementation file and run them again.
4. Construct a class named IntArray consisting of two private data members: a pointer to the beginning of the array, and an integer representing the size of the array. The public functions include a constructor and member functions that show all elements in the IntArray, and search a specified integer in the array.
Include the class IntArray within a complete program. The program should declare one object of type IntArray and accept and display data for the object to verify operation of the member functions.
5. Construct a class named Student consisting of an integer student idenfification number, an array of five floating point grades, and an integer representing the total number of grades entered. The constructor for this class should initialize all Student data members to zero. Included in the class should be member functions to
- enter a student ID number,
- enter a single test grade and update the total number of grades entered, and
- compute an average grade and display the student ID following by the average grade.
Include the class Student within a complete program. The program should declare two objects of type Student and accept and display data for the two objects to verify operation of the member functions.
6. Construct a class named Rectangle that has floating-point data members named length and width. The class should have a constructor that sets each data member to 0, member functions named perimeter() and area() to calculate the perimeter and area of a rectangle, respectively, a member function named getdata() to get a rectangle’s length and width, and a member function named showdata() that displays a rectangle’s length, width, perimeter, and area.
Include the Rectangle class within a working C++ program.
7. Given the class point which is defined as follows:
class point {
private:
int x,y;
public:
point( int xnew, int ynew);
void getdata();
void display();
};
point::point(int xnew, ynew) //constructor
{
x = xnew;
y = ynew;
}
void point::getdata()
{
cout << “Enter an integer value \n”;
cin >> x;
cout << “Enter an integer value \n”;
cin >> y;
}
void point::display()
{
cout << “Entered numbers are \n”;
cout << “ x = “ << x << ‘\t’ << “ y = “ << y << endl;
}
Write a main program that creates two point objects on the heap, displays these objects and then destroys the two objects.
8. Given the following program:
#include <iostream.h>
void main( )
{
int *ptr_a = new int[20];
int *ptr_n = new int;
int i;
cout << “ How many numbers are there ? \n”;
cin >> *ptr_n;
for (i = 0; i <= *ptr_n – 1; ++i){
cout << “ element : “;
cin >> ptr_a[i];
}
cout << “ Contents of the array \n”;
for (i = 0; i <= *ptr_n – 1; ++i){
cout << ptr_a[i];
cout << “\t”;
}
delete ptr_n;
delete [] ptr_a;
}
a. Explain the meaning of the program.
b. Run to determine the result of the program.
Exercise 8
1. Construct a class named Complex that contains two double-precision floating point data members named real and imag, which will be used to store the real and imaginary parts of a complex number. The function members should include a constructor that provides default values of 0 for each data member and a display function that prints an object’s data values.
Include the above class in a working C++ program that creates and displays the values of two Complex objects.
2. Construct a class named Car that contains the following three data members: a floating point variable named engineSize , a character variable named bodyStyle and an integer variable named colorCode. The function members should include (1) a constructor that provides default values of 0 for each numeric data members and ‘X’ for each character variable; and (2) a display function that prints the engine size, body style, and color code.
Include the class Car in a working C++ program that creates and displays two car objects.
3. Given the following class:
class Auto {
public:
Auto(char*, double);
displayAuto();
private:
char* szCarMake;
double dCarEngine;
};
Auto::Auto(char* szMake, double dEngine){
szCarMake = new char[25];
strcpy(szCarMake, szMake);
dCarEngine = dEngine;
}
Auto::displayAuto(){
cout<< “The car make: “<< szCarMake<< endl;
cout<< “The car engine size: “<< dCarEngine<< endl;
}
void main(){
Auto oldCar(“Chevy”, 351);
Auto newCar(oldCar);
oldCar.displayAuto();
newCar.displayAuto();
}
- Add an appropriate destructor to the class Auto.
- Include the class Auto in a working C++ program that creates two Auto objects on the heap, displays them and destroys them.
4. Given the following class:
class Employee{
public:
Employee(const char*, const char*);
char *getFirstName() const;
char *getLastName() const;
private:
char *firstName;
char *lastName;
};
Employee::Employee(const char *first, const char *last){
firstName = new char[strlen(first)+1];
strcpy(firstName, first);
lastName = new char[strlen(last)+1];
strcpy(lastName, last);
}
char *Employee::getFirstName() const{
return firstName;
}
char *Employee::getLastName() const{
return lastName;
}
void main(){
Employee *e1Ptr = new Employee(“Susan”, “Baker”);
Employee *e2Ptr = new Employee(“Robert”, “Jones”);
cout << “\n Employee 1: “
<< e1Ptr->getFirstName()
<< “ “ << e1Ptr->getLastName()
<< “\n Employee 2: “
<< e2Ptr->getFirstName()
<< “ “ << e2Ptr->getLastName()<< endl;
delete e1Ptr;
delete e2Ptr;
}
Add an appropriate destructor to the class Employee.
5. Given the following program which defines and uses the class Ob. What is the output of the main() function?
class Ob
{
private:
int field;
public:
Ob();
~Ob();
}
Ob::Ob()
{
field = 0;
cout << “Object created. “<< endl;
}
Ob::~Ob()
Cout << “Object detroyed. “<< endl;
}
void main()
{
Ob obj[6];
}
6. Given a base class named Circle which is defined as follows.
const double PI = 3.14159;
class Circle
{
protected:
double radius;
public:
Circle(double = 1.0); // constructor
double calcval();
};
// implementation section for Circle
// constructor
Circle::Circle(double r)
{
radius = r;
}
// calculate the area of a circle
double Circle::calcval()
{
return(PI * radius * radius);
}
a. Derive from the base class another class named Cylinder which contains an additional data member to store length. The only additional function members of Sphere should be a constructor and a calcval() function that returns the volume of the cylinder (Note: Volume = length*(pi*radius^2)).
b. Define another derived class name Sphere from the base Circle class. The only additional class members of Sphere should be a constructor and a calcval() function that returns the volume of the spere. (Note: Volume = 4/3*pi*radius^3).
c. Write the main() function in such a way that your program call all of the member functions in the Cylinder class and Sphere class.
7. Create a base class named Point that consists of an x and y coordinate. From this class, derive a class named Circle that has an additional data member named radius. For this derived class, the x and y data members represents the center coordinates of a circle. The function members of the first class should consist of a constructor and a distance() function that returns the distance between two points, where
distance = square-root((x2 – x1)^2 + (y2 – y1)^2)
Additionally, the derived class should have a constructor, an override distance() function that calculates the distance between circle centers, and a function named area that returns the area of a circle.
Include the two classes in a complete C++ program. Have your program call all of the member functions in each class. In addition, call the base class distance function with two Circle objects and explain the result returned by the function.
8.Create a base class named Rectangle that contains length and width data members. From this class, derive a class named Box having an additional data member named depth. The function members of the base Rectangle class should consist of a constructor and an area function. The derived Box class should have a constructor and an override function named area that returns the surface area of the box and a volume() function.
Include the two classes in a complete C++ program. Have your program call all of the member functions in each class and explain the result when the area() function is called using a Box object.
9. Modify the following code so that the overridden setSound() function executes correctly with the statements in the main() method.
class Instruments
{
public:
Instruments();
void setSound(char*);
char* getSound();
protected:
char* szSound;
}
Instruments:: Instruments(){
szSound = new char[25];
}
void Instruments::setSound(char* szSound){
szSound = “quiet”;
}
char* getSound(){
return szSound;
}
class Percussion: public Instruments
{
public:
Percussion();
void setSound(char*);
}
Percussion::Percussion(){
cout << “I repeat, the drum goes “
<< getSound() << endl;
}
void Percussion::setSound(char* szSound){
szSound = “boom”;
}
void main(){
Instruments* drums = new Percussion;
drums-> setSound();
cout<< “The drum goes “ << drums->getSound() << endl;
}