Programming Fundamentals in C 1.1
Programming Fundamentals in C 1.1
C++
By:
Dr Duong Tuan Anh
PROGRAMMING FUNDAMENTALS IN
C++
By:
Dr Duong Tuan Anh
Online:
< http://cnx.org/content/col10788/1.1/ >
CONNEXIONS
STUDENT MANUAL
1.1 Syllabus 1
1
2 CHAPTER 1. STUDENT MANUAL
Mr. Nguyen Quoc Viet Hung (nqvhung@cse.hcmut.edu.vn
4 )
Mr. Ly Hoang Hai (lhhai@cse.hcmut.edu.vn
5 )
Mr. Nguyen Xuan Minh (nxminh@cse.hcmut.edu.vn
6 )
Mr. Nguyen Van Doan (nvdoan@cse.hcmut.edu.vn
7 )
• arrays
• structures
• pointers
• object-oriented concepts such as information hiding, constructors, destructors, inheritance.
4 nqvhung@cse.hcmut.edu.vn
5 lhhai@cse.hcmut.edu.vn
6 nxminh@cse.hcmut.edu.vn
7 nvdoan@cse.hcmut.edu.vn
Pseudocode Descriptions. Pseudocode is stressed throughout the course. Flowchart symbols are
described, but are only used when visually presenting ow-of-control constructs.
Gentle Introduction to Object-Oriented Programming. In the course, there are two chapters
(7and 8) that provide a mini-course introduction to basic object-oriented programming concepts and design
techniques. Object oriented design techniques are illustrated in details in a Focus on Problem Solving section
of Chapter 7 with one complete application. For more advanced features of object-oriented programming in
C++, another course named Object-Oriented Programming which is oered one semester later will cover.
Exams
Exams are closed-book exams. Exams include one or more of: short answer, multiple choice, trace the
given code, debug the given code or given a problem description, produce a solution in the form of a short
program or a function(s).
The problems given in the exams are like those on exercises and lab work. The students who spend more
time and eort in doing exercises and lab assignments will certainly have better performance in the exams.
Exam scores are given in the range from 0 to 10.
1.1.12 CALENDAR
There are 16 sessions which compose of 14 lectures, 1 mid-term exam and 1 nal exam.
______Very Satised
______Satised
______Neutral
______Dissatised
______Very Dissatised
______Very Satised
______Satised
______Neutral
______Dissatised
______Very Dissatised
1. Based on the knowledge/skill you require to do your job, how would you want to change this course?
-
-
COURSE CONTENT
______Very Satised
______Satised
______Neutral
______Dissatised
______Very Dissatised
______Very Satised
______Satised
______Neutral
______Dissatised
______Very Dissatised
______Very Satised
______Satised
______Neutral
______Dissatised
______Very Dissatised
1. Rate the course materials (e.g., lecture notes, slides, lab manual, textbook).
______Very Satised
______Satised
______Neutral
______Dissatised
______Very Dissatised
INSTRUCTION
______Very Satised
______Satised
______Neutral
______Dissatised
______Very Dissatised
1. Rate the instructor's eectiveness (e.g., question handling, presentation, and ability to explain ideas).
______Very Satised
______Satised
______Neutral
______Dissatised
______Very Dissatised
1. Instruction comments:
FACILITIES AND EQUIPMENT
1. Rate the classroom facilities provided (e.g. ventilation, lightning, temperature, space, projector).
______Very Satised
______Satised
______Neutral
______Dissatised
______Very Dissatised
1. Rate the computer lab equipment provided (e.g., computers, software, Internet access).
______Very Satised
______Satised
______Neutral
______Dissatised
______Very Dissatised
1. Rate the lab/teaching assistant support. (enthusiasm, eectiveness, knowledge, skill, communication
ability).
______Very Satised
______Satised
______Neutral
______Dissatised
______Very Dissatised
1. Support comments.
Thank you for your comments.
1.2 Exercises 8
1.2.1 Exercise 1
1. Design an algorithm in owchart to nd the smallest number in a group of three real numbers.
2. Design an algorithm in owchart 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 owchart to read in a, b, c, d, e and f and then solve for X and Y.
4. Design an algorithm in owchart 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 owchart to read in a group of N numbers and compute the sum of them,
where N is also an input.
1.2.2 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;
8 This content is available online at <http://cnx.org/content/m27239/1.1/>.
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:
C = (5/9)(f 32).
1.2.3 Exercise 3
1. Write and run a program that performs the following steps:
C = (5/9)(f 32).
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 oating-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:
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:
Figure 1.3
1.2.4 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
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 rst
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.
1.2.5 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 nd 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 dierence 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 dierence 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 rst 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 nds 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 rst 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 ve double-precision numbers. Using a for loop and a cin statement, have your program accept
Figure 1.4
b. computing and displaying the average of heights and the average of weights of the students.
1.2.6 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 dene 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
1. Write a complete program that reads an integer n and invokes the function to compute its cube.
2. 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 nd 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 nd the largest element in
the array and print it out.
8. Given the following function that can nd a specied value in an array. If the search is successful,
this function returns the position of the specied 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:
9. A palindrome is a string that reads the same both forward and backward. Some examples are
Figure 1.5
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;
}
1.2.7 Exercise 7
1. Given the class student which is dened 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;
• 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 dened 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
}
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 coecients 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 le and one implementation le 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 specied 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 idencation number, an array of
ve oating 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 oating-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. point which is dened as follows:
Given the class
class point {
private:
int x,y;
public:
point( int xnew, int ynew);
void getdata();
void display();
1.2.8 Exercise 8
1. Construct a class named Complex that contains two double-precision oating 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 oating 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();
}
// 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. Dene 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 rst 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;
1.3 Assignments 9
1) Here is a challenging problem for those who know a little calculus. The Newton-Raphson method can be
used to nd the roots of any equation y(x) = 0.
1. Using the Newton-Raphson method, nd the two roots of the equation 3x^2 + 2x 2 = 0. (Hint: Stop
the loop when the dierence between the two approximations is less than 0.00001.)
2. Extend the program written for a) so that it nds the roots of any function y(x) = 0, when the function
for y(x) and the derivative of y(x) are placed in the code.
Using this information, write and test two functions, named det2() and det3(). The det2() function
should accept the four coecients of a 2 X 2 matrix and return its determinant. The det3() function should
accept the nine coecients of a 3 X 3 matrix and return its determinant by calling det2() to calculate the
required 2 X 2 determinants.
b. Write and run a C++ program that accepts the nine coecients of a 3 X 3 matrix in one main()
function, passes these coecients to det3() to calculate its determinant and then displays the calculated
determinant.
3) Your professor has asked you to write a C++ program that can be used to determine grades at the end
of the semester. For each student, who is identied by an integer number between 1 and 60, four examination
grades must be kept. Additionally, two nal grade averages must be computed. The rst grade average is
4) A magic square is an n X n matrix in which each of the integer values from 1 to n*n appears exactly
once and all column sums, row sums and diagonal sums are equal. For example, the following is a 3 X 3
magic square in which each row, each column, and each diagonal adds up to 15.
1. Write a function that accepts a two-dimensional array and integer n and checks if the n X n matrix
stored in the array is a magic square. The function should return true if it is a magic square and false
if it isn't. And also design it to return the magic sum of the magic square (sum of each row = sum
of each column = sum of each diagonal).
2. Write the driver program that:
5) A prime integer is any integer that is evenly divisible only by itself and 1. The Sieve of Eratosthenes is a
method of nding prime numbers. It operates as follows:
1. Create an array with all elements initialized to 1 (true). Array elements with prime subscripts will
remain 1. All other array elements will eventually be set to zero.
2. Starting with array subscript 2 (subscript 1 must be prime), every time an array element is found whose
value is 1, loop through the remainder of the array and set to zero every element whose subscript is a
multiple of the subscript for the element with value 1. For array subscript 2, all elements beyond 2 in
the array that are multiple of 2 will be set to zero (subscript 4, 6, 8, 10,etc.); for array subscript 3, all
elements beyond 3 in the array that are multiple of 3 will be set to zero (subscripts 6, 9, 12, 15, etc.);
and so on.
When this process is complete, the array elements that are still set to one indicate that the subscript is a
prime number. These subscripts can then be printed.
Write and run a C++ program that uses an array of 1000 elements to determine and print the prime
numbers between 1 and 999. Ignore element 0 of the array.
6) The Colossus Airlines eet consists of one plane with a seating capacity of 12. It makes one ight
daily. Write a seating reservation program with the following features:
a. The program uses an array of 12 structures. Each structure should hold a seat identication number,
a marker that indicates whether the seat is assigned and the name of the seat holder. Assume that the name
of a customer is not more than 20 characters long.
b. The program displays the following menu:
1. Show the list of customers together with their seat numbers in the order of the seat numbers
2. Assign a customer to a seat
3. Remove a seat assignment
4. Quit
c. The program successfully executes the promises of its menu. Choices (4) and (5) need additional input
from the user, which is done inside the respective functions.
d. After executing a particular function, the program shows the menu again, except for choice (6).
7) In this problem, a customer calls in an order for bicycles, giving his or her name, address, number
of bicycles desired, and the kind of bicycle. For now, all bicycles on one order must be the same kind.
Mountain bikes cost $269.95 each and street bikes $149.50. The total bill is to be calculated for the order.
Additionally, based on the user's knowledge of the customer, the customer is classied as either a good or bad
credit risk. Based on the input data, the program is to prepare shipping instructions listing the customer's
name, address, number and type of bikes, and the total amount due. Based on the creditworthiness of
the customer, the program must indicate on the shipping instructions if this is a C.O.D. (cash on delivery)
shipment or whether the customer will be billed separately.
The input and output requirements of this problem are relatively simple. On the input side, the items
that must be obtained are:
For output, a set of shipping instructions is to be generated. The instructions must contain the rst four
input items, the total cost of the order, and the type of billing. The total cost is obtained as the number of
bicycles ordered (input item 3) times the appropriate cost per bicycle, and the type of billing is determined
by the creditworthiness of the customer (input item 5). If the customer is creditworthy, a bill be sent;
otherwise requires cash payment on delivery. The customer record layout is as follows.
8) The Hanoi Tower is a puzzle consisting of a number of disks placed on three columns.
The disks all have dierent diameters and holes in the middle so they will t over the columns (see Figure
1). All the disks start out on column A. The object of the puzzle is to transfer all the disks from column
A to column C. Only one disk can be moved at a time, and no disk can be placed on a disk that is smaller
that itself.
The solution to this puzzle is easily expressed as a recursive procedure where each n disk solution is
dened in terms of an n-1 disk solution. To see how this works, rst consider a one-disk puzzle. Clearly, this
has a simple solution, where we move the disk from column A to column C.
Now consider the n-disk problem. Moving n disks can be viewed in terms of moving only n 1 disks
(hence, the recursion) as follows:
a) Move n-1 disks from column A to column B, using column C as a temporary holding area.
b) Move the last disk (the largest) from A to from C.
c) Move the n-1 disks from column B to column C, using column A as a temporary holding area.
The process ends when the last task involving n =1 disk, i.e., the base case. This is accomplished by
trivially moving the disk.
Write a program to solve the Hanoi Tower puzzle. Use a recursive function with four parameters:
a) The number of disks to be moved
9) a. Create a class named Fractions having two integer data members named for a fraction's numerator
and denominator. The class's default constructor should provide both data members with default values
of 1 if no explicit user initialization is provided. Additionally, provide member functions for displaying
an object's data values. Also provide the class with the member functions that are capable of adding,
subtracting, multiplying, and dividing two Fraction objects according to the following formulas:
Sum of two fractions: a/b + c/d = (ad +cb)/bd
Dierence of two fractions: a/b c/d = (ad cb)/bd
Product of two fractions: (a/b)X (c/d) = ac/bd
Division of two fractions: (a/b)/(c/d) = ad/cb
b. Include the class written for a) in a working C++ program that tests each of the class's member
functions.
10) A stack is an ordered collection of data items in which access is possible only at one end, called the
top of the stack with the following basic operations:
1. Push: add an element to the top of the stack.
2. Pop: remove and return the top element of the stack.
3. Check if the stack is empty
4. Check if the stack is full.
It would be nice to have a stack class, because we could then use it to easily develop some applications
which need stack data structure.
a. For the moment, assume that we need to dene an integer stack class. Since a stack must stores a
collection of integers, we can use an integer array to model the stack and a pointer named Top to indicate
the location of the top of the stack. The array should have a xed size. So we can begin the declaration of
the class by selection two data members:
• Provide an integer array data member to hold the stack elements (the size of the array is a constant).
b. After dening the stack class, write a main() function which does the following tasks:
c. Next, apply the stack data structure in solving the following problem: write a program that accepts a
string from the user and prints the string backward. (Hint: Use a character stack)
1.4 Labworks 10
1.4.2.2 2. EXPERIMENT
2.1) Test the following program:
#include <iostream.h>
int main()
{
const float PI=3.14159;
float radius = 5;
float area;
area = radius * radius * PI; // Circle area calculation
cout The area is area with a radius of 5.\n;
radius = 20; // Compute area with new radius.
area = radius * radius * PI;
cout The area is area with a radius of 20.\n;
return 0;
}
1. 1 + 2 * 4 / 2
2. (1 + 2) * 4 / 2
3. 1 + 2 * (4 / 2)
4. 9 % 2 + 1
5. (1 + (10 - (2 + 2)))
#include <iostream.h>
void main()
{
if (!0)
{ cout C++ By Example \n; }
int a = 0;
if ( a !=0 && 2/a >0 )
cout hello;
}
2.7) Write a program that inputs the three grades for mathematics, physics and chemistry. And then it
displays the average of the three grades in the following format:
Figure 1.12
• if
• if ... else
• switch
1.4.3.2 2. EXPERIMENT
2.1) Run the following program:
// BEEP : `\x07'
#include <iostream.h>
#define BEEP cout \a \n
int main()
{
int num;
cout Please enter a number ;
2.7) Write a program that can calculate the fee for a taxi ride. The formula is as follows:
The program has to input the total distance (in km) and calculate the charge.
2.8) Write a program that inputs a date consisting of day, month, and year components. Check if the
date is valid or not and if it is, determine what its previous day is. Example: if the date is 01/01/2003 then
its previous day is 31/12/2002.
• for
• while
• do. . .while
1.4.4.2 2. EXPERIMENT
2.1) Determine the result of the following code segment. Explain this result.
int a = 1;
while (a < 4)
{
cout This is the outer loop\n;
a++;
while (a <= 25)
{
break;
cout This prints 25 times\n;
}
}
2.2) Test the following program.
#include <iostream.h>
#include <iomanip.h>
void main()
{
float total_grade=0.0;
float grade_avg = 0.0;
float grade;
int grade_ctr = 0;
do
{
cout What is your grade? (-1 to end) ;
cin grade;
if (grade >= 0.0)
{
total_grade += grade; // Add to total.
grade_ctr ++;
end=5;
step=1;
for (; start>=end;)
{
cout i \n;
start+=step;
end;
}
2.5) Write a C++ program to convert Celsius degrees to Fahrenheit. The Celsius degrees increase from 5
to 50 with the increment of 5 degrees. The resultant table should be in the following form with appropriate
headings:
Figure 1.13
Figure 1.14
1.4.5.2 2. EXPERIMENT
2.1) Test the following program.
#include <iostream.h>
const int NUM = 8;
void main()
{
int nums[NUM];
int total = 0; // Holds total of user's eight numbers.
int ctr;
for (ctr=0; ctr<NUM; ctr++)
{
cout Please enter the next number...;
cin nums[ctr];
total += nums[ctr];
}
cout The total of the numbers is total \n;
return;
}
2.2) If the array weights is declared as in the following statement, then what the value of weights[5] is ?
int weights[10] = {5, 2, 4};
2.3) Given the statement:
char teams[] = {`E','a','g','l','e','s','\0', 'R', `a','m','s','\0'};
which of the following statement is valid?
a. cout teams;
b. cout teams+7;
c. cout (teams+3);
d. cout teams[0];
e. cout (teams+0)[0];
f. cout (teams+5);
2.4) Given the array declaration:
int grades[3][5] = {80,90,96,73,65,67,90,68,92,84,70, 55,95,78,100};
Determine the value of the following subscripted variables:
a. grades[2][3]
b. grades[2][4]
c. grades[0][1]
2.5) Write a C++ program that inputs an array consisting of n single-precision oating point numbers
and nds the smallest element in the array. (n is an integer that is entered by the user).
2.6) Write a C++ program that inputs an integer array and nds the last element in the array.
2.7) Write a C++ program that inputs an integer array and then inserts the integer value X in the rst
position in the array.
2.8) Write a C++ program that inputs an integer array and checks if all the elements in the array are
unique (i.e. we can not nd any pair of elements that are equal to each other).
2.9) Write a C++ program that inputs a matrix and then transposes it and displays the transposed
matrix. Transposing a square matrix is to swap:
a(i,j) <==> a(j,i) for all i, j
For example, given the matrix
Figure 1.15
Figure 1.16
2.10) Write a C++ program that inputs an integer n and two square matrices with order of n. Then the
program calculates the multiplication of the two matrices and displays the resultant matrix.
1.4.6.2 2. EXPERIMENT
2.1) Write a C++ program that accepts a string of characters from a terminal and displays the hexadecimal
equivalent of each character.
(Hint: Use the cin.getline() function to input a string)
2.2) Write a C++ program that accepts a two strings of characters from a keyboard and displays the
concatenation of the two strings.
(Hint: Use the cin.getline() function to input a string)
2.3) Write and run a program that reads three strings and prints them out in an alphabetical order.
(Hint: Use the strcmp() function).
2.4) Write a C++ program that accepts a string of characters from a terminal and converts all lower-case
letters in the string to upper-case letters.
2.5) a. Using the data type
struct MonthDays
{
char name[10];
int days;
};
dene an array of 12 structures of type MonthDays. Name the array months and initialize the array with
the names of the 12 months in a year and the number of days in each month.
b. Include the array created in a) in a program that displays the names and number of days in each
month.
2.6) a. Declare a data type named Car, which is a structure consisting of the following information for
each car:
Figure 1.17
b. Using the data type dened in a) write a C++ program that inputs the data given in the above table
into an array of 5 structures., and then computes and displays a report consisting of 3 columns: car-number,
kms-driven and gas-litres-used.
1.4.7.2 2. EXPERIMENT
2.1) Given the following function:
int square(int a)
{
a = a*a;
return a;
}
a. Write a C++ program that reads an integer n and invokes the function to compute its square and
displays this result.
b. Rewrite the function so that the parameter is passed by reference. It is named by square2. Write a
C++ program that reads an integer x and invokes the function square2 to compute its square and displays
this result and then displays the value of x. What is the value of x after the function call? Explain this
value.
2.2) Read the following function that can compute the largest integer which square is less than or equal
to a given integer.
int Intqrt(int num)
{
int i;
i = 1;
do
++ i
while i*i <= num;
return(i 1);
}
Write a C++ program that inputs an interger n and invokes the function Intqrt to compute the largest
integer which square is less than or equal to n.
2.3) a. Write a function that can nd the average of all the elements in a double precision oating point
array that is passed to the function as a parameter.
b. Write a C++ program that inputs a double precision oating point array and invokes the above
function to nd the average of all elements in the array and displays it out.
2.4) Write a C++ function that checks if a square matrix with order of n is symmetric or not. And then
write a C++ program that inputs a square matrix with order of n and then checks if it is symmetric or not.
2.5) A palindrome is a string that reads the same both forward and backward. Some examples are
Figure 1.18
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 `*'.
2.6) Write a boolean function that can checks if all the elements in integer array are unique (i.e. we can
not nd any pair of elements that are equal to each other).
Write a C++ program that inputs an integer array and invokes the function to check if all the elements
in integer array are unique.
2.7) Given the following formula for computing the number of combinations of m things out of n, denote
C(n, m).
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
2.8) The greatest common divisor of two positive integers is the largest integer that is a divisor of both of
them. For example, 3 is the greatest common divisor of 6 and 15, and 1 is the greatest common divisor of
15 and 22. Here is a recursive function that computes the greatest common divisor of two positive integers:
int gcd(int p, int q)
{
int r ;
if (( r = p%q == 0)
return q ;
else
return gcd(q, r) ;
}
1.4.8.2 2. EXPERIMENT
2.1) Run the following program to determine the size of two data types long and byte.
# include <iostream.h>
void main()
{
byte* a;
long* b;
coutsizeof(a)endl;
coutsizeof(b)endl;
}
2.2) Given the following code segment:
float pay;
float *ptr_pay;
pay=2313.54;
ptr_pay = &pay;
determine the values of the following expressions:
a. pay
b. *ptr_pay
c. *pay
d. &pay
2.3) Read for understanding the following program:
#include<iostream.h>
void main()
{
int a;
int *aPtr; // aPtr is a pointer to an integer
a = 7;
aPtr = &a; //aPtr set to address of a
cout The address of a is &a
\nThe value of aPtr is aPtr;
cout \n\nThe value of a is a
\nThe value of *aPtr is *aPtr
endl;
}
Run the program and explain the output.
2.4) Given the following array and pointer declarations:
int ara[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *ip1, *ip2;
Determine which of the following assignments are valid.
a. ip1 = ara;
b. ip2 = ip1 = &ara[3];
x1 = &c1; x2 = &c2;
y1 = &d1; y2 = &d2;
swap(a, x1,x2,y1,y2);
couta[0]a[1]
*x1*x2
*y1*y2;
swap(a, x1,x2,y1,y2);
couta[0]a[1]
*x1*x2
*y1*y2;
}
void swap(int a[], int *c1, int *c2, int *d1, int *d2)
{
a[0] = 2 ; a[1] =1;
*c1=2, *c2 =1;
int* temp = d1;
d1 =d2;
d2 = temp;
}
2.6) Write a declaration to store the following values into an array named rates: 12.9, 18.6, 11.4, 13.7,
9.5, 15.2, 17.6. Include the declaration in a program that displays the values in the array using pointer
notation.
2.7) Given the following function that can nd the largest element in an integer array. Notice that the
function scans the elements in the array using 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 nd the largest
element in that array and displays the result out.
2.8) In the following program, the function str_output() can display a string which is passed to it as a
a pointer parameter:
#include<iostream.h>
#include<string.h>
#define MAX 80
void str_output(char *);
int main()
{
char a[MAX], b[MAX];
cin.getline(a, MAX, '\n');
str_output(a);
cout endl;
strcpy(b,a);
str_output(b);
cout endl;
return 0;
}
void str_output(char *ptr)
{
. . .. . .. . ...
}
a. Complete the function str_output() which displays each element in the string using pointer notation.
b. Run to test the whole program.
2.9) 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.
1.4.9.2 2. EXPERIMENT
2.1) a. Read to understand the following program which uses the class student. Organize the program in
one source program and run it on a C++ environment.
#include<iostream.h>
class student{
private:
long int rollno;
int age;
char sex;
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()
{
coutendl;
cout " Roll no = " rollno endl;
cout " Age =" age endl;
cout " Sex =" sex endl;
cout " Height =" height endl;
cout " Weight =" weight endl;
}
void main()
{
student a;
cout " Enter the following information " endl;
a.getinfo();
cout " \n Contents of class " endl;
a.disinfo();
}
b. Reorganize the program into an interface le and an implementation le and then run the program.
2.2) Given the class student as dened in 2.1.a. Write a complete C++ program in which the main()
function creates an array of size 10 to store student objects and prompts the user to enter the data for the
student objects in the array and then displays the objects in the array.
2.3) Given the class student as dened in 2.1.a. Write a complete C++ program in which the main()
function performs the following tasks:
• A constructor with no parameters that assigns 0 to two data members of the created object.
• A constructor with two single-precision oating-point parameters which assigns two parameters to the
two data members of the created object.
• Function perimeter() to compute the perimeter of the rectangle.
• Function area() to compute the area of the rectangle.
• Function getdata( ) to prompt the user to enter the length and width for a rectangle.
• Function showdata( ) to display length, width, perimeter and area of a rectangle.
Include the class Rectangle in a complete C++ program. The main() function of this program creates two
Rectangle objects using the two constructors respectively and displays the data of the two objects to check
the working of all the member functions.
Then modify the program by replacing the two above constructor functions by a constructor with default
arguments.
2.6) Dene a class named CStudent which consists of the following data members:
• the constructor which assigns the initial values 0 to all data members of each Cstudent objects.
2.7 ) Test the following program which uses a run-time allocated array.
#include <iostream.h>
void main()
{
int num;
cout Please enter the numbers of input:
cinnum;
int a = new int [num];
int total = 0; // Holds total of user's eight numbers.
int ctr;
for (ctr=0; ctr<num; ctr++)
{
cout Please enter the next number...;
cin a[ctr];
total += a[ctr];
}
cout The total of the numbers is total \n;
return;
delete [] a;
}
2.8) Given a class named IntArray that contains 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 every element in the IntArray, and show the rst IntArray element only.
The denition of the class IntArray is as follows:
// IntArray.h
class IntArray
{
private:
int* data; //pointer to the integer array
int size;
public:
IntArray(int* d, int s);
void showList();
void showFirst( );
};
// IntArray.cpp
IntArray::IntArray(int* d, int s)
{
data = d;
size = s;
}
void IntArray::showList()
{
cout"Entire list:" endl;
for(int x = 0; x< size; x++)
cout data[x]endl;
cout "" endl;
}
void IntArray::showFirst()
{
cout "First element is ";
cout data[0] endl;
}
a. Add to the class IntArray one more member function named ndMax which returns the largest element
in the array.
b. Write a main program that instantiates one array of integers and then displays the array, the rst
element and the largest element of the array.
1.4.10.2 2. EXPERIMENT
2.1) Run the following program in a C++ environment.
class Int{
private:
int idata;
public:
Int(){
idata=0;
cout"default constructor is called"endl;
}
Int(int d=9){
idata=d;
cout"constructor with argument is called"endl;
}
void showData(){
cout"value of idata: "idataendl;
}
};
void main()
{
Int i;
Int j(8);
Int k=10;
}
a. Explain why the program incurs a compile-time error.
b. Modify the program in order to remove the above error. Run the modied program.
2.2) Run the following program in a C++ environment.
class Vector{
private:
int *value;
void main()
{
Vector v(5);
v.showdata();
Vector v2(v);
v2.showdata();
}
a. Explain why the program incurs one memory error at run-time.
b. Now add the following code segment in the Vector class denition.
Vector(const Vector& v){
dimension = v.dimension;
value=new int[dimension];
for (int i=0; i<dimension; i++)
value[i]=v.value[i];
}
Check if the program still incurs the memory error or not. Explain why.
2.3) a. Test the following program in a Visual C++ environment:
class some{ // code segment a
public:
∼some() {
cout"some's destructor"endl;
}
};
void main() {
some s;
s.∼some();
}
What is the output of the above program during execution? Explain the output.
void main()
{
some s;
// s.∼some();
}
What is the output of the above program during execution? Explain the output.
c. In the main() function of the program in b, if we remove the two slashes (//) before the statement
s.∼some(); then what the result is when the program is executed ? Explain why.
2.4) Given the class denition as follows:
class Auto {
public:
Auto(char*, double);
displayAuto(char*, double);
private:
char* szCarMake;
double dCarEngine;
};
Auto::Auto(char* szMake, double dEngine){
szCarMake = new char[25];
strcpy(szCarMake, szMake);
dCarEngineSize = dCarEngine;
}
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();
}
1. Add an appropriate copy constructor to the Auto class .
2. Add an appropriate destructor to the Auto class .
Figure 1.19
1.4.11.2 2. EXPERIMENT
2.1) Given the Point class dened as follows.
class Point{
private:
int color;
protected:
double x;
double y;
public:
Point(double x=0, double y=0){
this->x=x; this->y=y;
}
void move(double dx, double dy){
x=x+dx;
y=y+dy;
}
∼Point(){
cout"Destructor Point called";
}
};
Derive from the class Point, another class named Point_Derive1 class, which is dened as follows.
class Point_Derive1:public Point{
private:
double z;
public:
Point_Derive1();
void move(double dx, double dy, double dz);
∼Point_Derive1();
};
a. List out the data members and member functions of the Point_Derive1 class. And determine the
access specier of each of these members.
Derive from the class Point, another class named Point_Derive2 class, which is dened as follows.
class Point_Derive2:protected Point{
private:
double z;
public:
Point_Derive1();
void move(double dx, double dy, double dz);
∼Point_Derive1();
};
b. List out the data members and member functions of the Point_Derive2 class. And determine the
access specier of each of these members.
Derive from the class Point, another class named Point_Derive3 class, which is dened as follows.
class Point_Derive3:private Point{
private:
double z;
public:
Point_Derive1();
void move(double dx, double dy, double dz);
∼Point_Derive1();
};
c. List out the data members and member functions of the Point_Derive3 class. And determine the
access specier of each of these members.
2.2) Given the following program in which the Cylinder class is a subclass derived from the Circle class
#include <iostream.h>
#include <math.h>
const double PI = 2.0 * asin(1.0);
// class declaration
class Circle
{
protected:
double radius;
public:
Circle(double = 1.0); // constructor
double calcval();
};
• x, y coordinates
• a constructor with two parameters representing x, y coordinates (their default values are allowed to be
0)
• a member function named display, which prints out two coordinates on the screen.
• A member function named getInfo, which accepts two input data from the user for x, y coordinates.
• Two member functions named setX, setY to update values to x, y, respectively.
• Two member functions named getX, getY to retrieve values from x, y, respectively.
• A member function named distance, which accepts as parameter an object of class CPoint and calculates
the distance from the object invoking the function to the parameter object.
b. Construct a derived class named CPoint_3D from the class CPoint, described as follows:
c. Include the class constructed in a) and b) in a working C++ program. Have your program call all of the
member functions in the CPoint_3D class.
• The program uses an array of 12 structures. Each structure should hold a seat identication number,
a marker that indicates whether the seat is assigned and the name of the seat holder. Assume that the
name of a customer is not more than 20 characters long.
• The program successfully executes the promises of its menu. Choices (4) and (5) need additional input
from the user which is done inside the respective functions.
• After executing a particular function, the program shows the menu again, except for choice (6).
1.4.12.2 PROJECT 2
This project aims to review all the chapters from Chapter 7 (Introduction to Classes) to Chapter 8 (Object
Manipulation - Inheritance) which focus on the basics of object-oriented programming.
An example of Project 2 can be described as follows:
A stack is an ordered collection of data items in which access is possible only at one end, called the top
of the stack with the following basic operations:
It would be nice to have a stack class, because we could then use it to easily develop some applications
which need stack data structure.
For the moment, assume that we need to dene an integer stack class. Since a stack must stores a
collection of integers, we can use an integer array to model the stack and a pointer named Top to indicate
the location of the top of the stack. The array should have a xed size. So we can begin the declaration of
the class by selection two data members:
As for the member functions of the stack class, we have to dene 5 member functions: the constructor which
creates an empty stack and four other member functions (push, pop, check if the stack is empty, check if the
stack is full).
After dening the stack class, write a main() function which does the following tasks:
Next, apply the stack data structure in solving the following problem: write a program that accepts a string
from the user and prints the string backward. (Hint: Use a character stack)
LECTURE NOTES
2.1 Introduction to Computers and Programming 1
57
58 CHAPTER 2. LECTURE NOTES
ROM (read only memory) contains fundamental instructions that cannot be lost or changed by the user.
ROM is non-volatile.
Virtually all secondary storage is now done on magnetic tapes, magnetic disks and CD-ROMs.
A magnetic hard disk consists of either a single rigid platter or several platters that spin together on
a common spindle. A movable access arm positions the read and write mechanisms over, but not quite
touching, the recordable surfaces. Such a conguration is shown in Figure 2.
Machine languages and assembly languages are called low-level languages since they are closest to com-
puter hardware.
Figure 2.4: Four development and design steps in commercial programming projects
• Program description
• Algorithm development and changes
• Well-commented program listing
• Sample test runs
• User's manual
To illustrate an algorithm, we consider the simple program that computes the pay of a person. The
owchart for this program is given in the Figure below.
Note: Name, Hours and Pay are variables in the program.
Note:
NUM = NUM + 1
means old value of NUM + 1 becomes new value of NUM .
The above algorithm can be described in pseudocode as follows:
NUM = 4
do
SQNUM = NUM*NUM
Print NUM, SQNUM
NUM = NUM + 1
while (NUM <= 9)
You can compare the pseudo-code and the owchart in Figure above to understand the meaning of the
do. . . while construct used in the pseudo-code.
• Identiers must begin within an uppercase or lowercase ASCII letter or an underscore (_).
• You can use digits in an identier, but not as the rst character. You are not allowed to use special
characters such as $, &, * or %.
• Reserved words cannot be used for variable names.
Examples:
DegToRadintersectaddNums
FindMax1_densityslope
Examples of invalid identiers:
1AB3
E%6
while
Note: C++ is a case-sensitive language (i.e. upper and lower case characters are treated as dierent
letters).
int main()
{
2.2.1.5 Comments
Comments are lines that you place in your code to contain various type of remarks. C++ support two types
of comments: line and block.
C++ line comments are created by adding two slashes (//) before the text you want to use as a comment.
Block comments span multiple lines. Such comments begin with /* and end with the symbols */.
Example:
void main()
{
/*
This line is part of the block comment.
This line is also part of the block
comment.
*/
cout Line comment 1 ;
cout Line comment 2 ;
// This line comment takes up an entire line.
}
All programs should contain comments. They are
remarks, insights, wisdom in code without aecting the program. The compiler ignores comments
.
Exponential notation, or scientic notation is a way of writing a very large numbers or numbers with
many decimal places using a shortened format.
2.0e11 means 2*1011
C++ supports three dierent kinds of oating-point numbers:
Example: Let us use the precedence rules to evaluate an expression containing operators of dierent
precedence, such as 8 + 5*7%2*4. Because the multiplication and modulus operators have a higher prece-
dence than the addition operator, these two operations are evaluated rst (P2), using their left-to-right
associativity, before the addition is evaluated (P3). Thus, the complete expression is evaluated as:
Example:
int num = 15;
float grade1 = 87.0;
Variable declarations are just the instructions that tell the compiler to allocate memory locations for the
variables to be used in a program.
A variable declaration creates a memory location but it is undened to start with, that means it's empty.
Example
#include <iostream.h>
int main()
{
float price1 = 85.5;
float price2 = 97.0;
float total, average;
a = 22;
cout "The value stored in a is " a endl;
cout "The address of a = " &a endl;
return 0;
}
The output of the above program:
The value stored in a is 22
The address of a = 0x0065FDF4
The display of addresses is in hexadecimal notation.
When you are modifying an int with short or long, the keyword int is optional.
Now all the built-in data types provide by C++ are given in the following list, ordered descendingly by
the size of the data types.
Data types
long double
double
oat
unsigned long
long int
unsigned int
int
short in
char
• when both operands are character, short or integer data types, the result of the expression is an
integer value.
• when one of the operand is a long integer, the result is a long integer, unless one of the operand
is an unsigned integer. In the later case, the other operand is converted to an unsigned integer
value and the resulting value of the expression is an unsigned value.
• when one or both operands are oats, the result of the operation is a oat value;
• when one or both operands are doubles, the result of the operation is a double value;
• when one or both operands are long doubles, the result of the operation is a long double value;
Notice that converting values to lower types can result in incorrect values. For example, the oating point
value 4.5 gives the value 4 when it is converted to an integer value. The following table lists the built-in
data types in order from highest type to lowest type.
numin2 = 110;
lines1 = numin1*(numin1 1)/2;
lines2 = numin2*(numin2 1)/2;
cout The number of initial lines is lines1 .\n;
cout There are lines2 lines1
additional lines needed.\n;
return 0;
}
radius = 2.5;
height = 16.0;
3 This content is available online at <http://cnx.org/content/m27210/1.1/>.
Assignment statements such as sum += 10 or its equivalent, sum = sum + 10, are very common in C++
programming.
The increment (++) and decrement () unary operators can be used as prex or postx operators to
increase or decrease value.
A prex operator is placed before a variable and returns the value of the operand after the operation
is performed.
A postx operator is placed after a variable and returns the value of the operand before the operation
is performed.
Prex and postx operators have dierent eects when used in a statement
b = ++a;
will rst increase the value of a to 6, and then assign that new value to b. It is equivalent to
a = a +1;
b = a;
On the other hand, execution of the statement
b = a++;
will rst assign the value of 5 to b, and then increase the value of a to 6. It is now equivalent to
b = a;
a = a + 1;
The decrement operators are used in a similar way.
Example
// Preincrementing and postincrementing
#include <iostream.h>
int main()
{
int c;
c = 5;
cout c endl; // print 5
cout c++ endl; // print 5 then postincrement
cout c endl endl; // print 6
c = 5;
cout c endl; // print 5
cout ++c endl; // preincrement then print 6
cout c endl; // print 6
Example:
cout | setw(10)
setioflags(ios::fixed) setprecision(3) 25.67|;
causes the printout
- setiosags: This manipulator is used to control dierent input and output settings.
setioag(ios::xed) means the output eld will use conventional xed-point decimal notation.
setiosag(ios::showpoint) means the output eld will show the decimal point for oating point number.
setiosag(ios::scientic) means the output eld will use exponential notation.
Note: In the absence of the ios::xed ag, a oating point number is displayed with a default of 6
signicant digits. If the integral part of the number requires more than 6 digits, the display will be in
exponential notation.
Below are some other format ags for use with setiosags().
Example
// This program will illustrate output conversions
#include <iostream.h>
#include <iomanip.h>
int main()
{
cout "The decimal (base 10) value of 15 is " 15 endl
"The octal (base 8) value of 15 is "
setiosflags(ios::oct) 15 endl
"The hexadecimal (base 16) value of 15 is "
setiosflags(ios::hex) 15 endl;
return 0;
}
The output of the above program:
The decimal (base 10) value of 15 is 15
The octal (base 8) value of 15 is 17
The hexadecimal (base 16) value of 15 is f
To designate an octal integer constant, the number must have a leading 0. Hexadecimal number are
denoted using a leading 0x.
Example
// Octal and hexadecimal integer constant
#include <iostream.h>
int main()
{
cout "The decimal value of 025 is " 025 endl
"The decimal value of 0x37 is " 0x37 endl;
return 0;
}
The output of the above program:
The decimal value of 025 is 21
Except abs(a), the functions all take an argument of type double and return a value of type double.
Example
// this program calculates the area of a triangle
// given its three sides
#include <iostream.h>
#include <math.h>
int main()
{
2.3.3.1 Casts
We have already seen the conversion of an operand's data type within mixed-mode expressions and across
assignment operators. In addition to these implicit data type conversions that are automatically made within
mixed-mode expressions and assignment, C++ also provides for explicit user-specied type conversion. This
method of type conversion is called casting. The word cast is used in the sense of casting into a mold.
Casting or type casting, copies the value contained in a variable of one data type into a variable of
another data type.
The C++ syntax for casting variables is
variable = new_type( old_variable);
where the new_type portion is the keyword representing the type to which you want to cast the variable.
Example:
int iNum = 100;
float fNum;
fNum = float (inum);
If you do not explicitly cast a variable of one data type to another data type, then C++ will try to
automatically perform the cast for you.
{
int integer1, integer2, sum; // declaration
int main()
radius = 2.0;
circumference = 2.0 * PI * radius;
cout "The circumference of the circle is "
circumference endl;
return 0;
}
The output of the above program:
The circumference of the circle is 12.5664
Figure 2.19
Realizing the each line in the display can only be produced by executing a cout statement, it should
be clear that four such statements must be executed. Additionally, since each output line contains three
computed values, each cout statement will have three items in its expression list.
The only input to the program consists of the value of x. This will, of course, require a single prompt
and a cin statement to input the necessary value.
Example:
a = = b
(a*b) != c
s == `y'
x <= 4
The value of a relational expression such as a > 40 depends on the value stored in the variable a.
The NOT operator,!, is used to change an expression to its opposite state; thus, if the expression has any
nonzero value (true),! expression produces a zero value (false). If an expression is false,! expression is true
(and evaluates to false).
Example:
(age > 40) && (term < 10)
(age > 40) || (term < 10)
!(age > 40)
( i==j) || (a < b) || complete
The relational and logical operators have a hierarchy of execution similar to the arithmetic operators.
The following table lists the precedence of these operators in relation to the other operators we have used.
2.4.3 Example 1
We construct a C++ program for determining income taxes. Assume that these taxes are assessed at 2%
of taxable incomes less than or equal to $20,000. For taxable income greater than $20,000, taxes are 2.5%
of the income that exceeds $20,000 plus a xed amount of $400. (The owchart of the program is given in
Figure 2.)
#include <iostream.h>
#include <iomanip.h>
2.4.4 Example
The following program displays an error message for the grades that is less than 0 or more than 100.
#include <iostream.h>
int main()
{
int grade;
2.4.6 Example
The following program calculates the monthly income of a computer salesperson using the following com-
mission schedule:
#include <iostream.h>
#include <iomanip.h>
int main()
{
float monthlySales, income;
return 0;
}
The output of the program:
Enter the value of monthly sales: 36243.89
The income is $4674.27
cout "Enter a number to find the state where a city is located. " endl;
cout 1. Boston endl;
cout "2. Chicago" endl;
cout "3. Los Angeles endl;
cout "4. Miami endl;
cout "5. Providence endl;
cin iCity;
switch (iCity)
{
case 1:
cout "Boston is in Massachusetts " endl;
break;
case 2:
cout "Chicago is in Illinois " endl;
break;
case 3:
cout "Los Angeles is in California " endl;
break;
case 4:
cout "Miami is in Florida " endl;
break;
case 5:
cout "Providence is in Rhode Island " endl;
break;
default:
cout You didn't select one of the five cities endl;
} // end of switch
return 0;
}
The output of the above program:
Enter a number to nd the state where a city is located.
1. Boston
2. Chicago
3. Los Angeles
4. Miami
5. Providence
3
Los Angeles is in California
The switch statement is a clean way to implement multi-way selection (i.e., selecting from among a
number of dierent execution paths), but it requires an expression that evaluates to an integral value at
compile-time.
When writing a switch statement, you can use multiple case values to refer to the same set of statements;
the default label is optional. For example, consider the following example:
switch(number)
{
case 1:
cout Have a Good Morning\n;
break;
case 2:
cout Have a Happy Day\n;
break;
case 3:
case 4:
case 5:
cout Have a Nice Evening\n;
}
2.4.9 Example
#include <iostream.h>
int main()
{
enum color{red, green, yellow};
enum color crayon = red;
cout \nThe color is crayon endl;
cout Enter a value: ;
cin crayon;
if (crayon == red)
cout The crayon is red. endl;
else if (crayon == green)
cout The crayon is green. endl;
else if (crayon== yellow)
cout The crayon is yellow. endl;
else
cout The color is not defined. \n endl;
return 0;
1. while structure
2. for structure
3. do-while structure
Each of these statements requires a condition that must be evaluated, which is the second required element
for constructing repeating sections of code. Valid conditions are similar to those used in selection statements.
If the condition is true, the code is executed; otherwise, it is not.
The third required element is a statement that initially sets the condition. This statement must always
be placed before the condition is rst evaluated to ensure correct loop execution the rst time the condition
is evaluated.
Finally, there must be a statement within the repeating section of code that allows the condition to
become false. This is necessary to ensure that, at some point, the repetition stop.
The condition being tested can be evaluated at either (1) the beginning or (2) the end of the repeating
section of code.
5 This content is available online at <http://cnx.org/content/m27289/1.1/>.
If the test occurs at the beginning of the loop, the type of loop is called a pre-test loop or entrance-
controlled loop. If the test occurs at the end of the loop, the type of loop is called a post-test loop or
exit-controlled-loop.
In addition to where the condition is tested (pretest or posttest), repeating sections of code are also
classied. In a xed count loop, the condition is used to keep track of how many repetitions have occurred.
In this kind of loops, a xed number of repetitions are performed, at which point the repeating section of
code is exited.
In many situations, the exact number of repetitions are not known in advance or the items are too
numerous to count beforehand. In such cases, a variable condition loop is used. In a variable condition loop,
the tested condition does not depend on a count being achieved, but rather on a variable that can change
interactively with each pass through the loop. When a specied value is encountered, regardless of how many
iterations have occurred, repetitions stop.
2.5.3 Example
// this program computes the sum of 10 first integers starting from 1
#include <iostream.h>
int main()
{
const int N = 10
int sum = 0;
int count = 1; // initialize count
while (count <= N){
sum = sum + count;
count++; // increment count
}
cout The sum is sum endl;
return 0;
}
The output of the above program:
The sum is 55
In the above program, the loop incurs a counter-controlled repetition. Counter-controlled repetition
requires:
2.5.3.1 Example
#include <iostream.h>
int main()
{
int i;
i = 10;
while (i >= 1)
{
cout i " ";
i; // subtract 1 from i
}
return 0;
}
The output of the above program:
1. 9 8 7 6 5 4 3 2 1
2.5.5 Example
// Class average program with counter-controlled repetition
#include <iostream.h>
int main()
{
int total, // sum of grades
gradeCounter, // number of grades entered
grade, // one grade
average; // average of grades
// initialization phase
total = 0;
gradeCounter = 1; // prepare to loop
// termination phase
average = total / 10; // integer division
cout "Class average is " average endl;
return 0;
}
The following is a sample run of the above program:
Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
2.5.5.1 Sentinels
In programming, data values used to indicate either the start or end of a data series are called sentinels.
The sentinel values must be selected so as not to conict with legitimate data values.
Example
#include <iostream.h>
int main()
{
float grade, total;
grade = 0;
total = 0;
cout "\nTo stop entering grades, type in any number less than 0.\n\n";
cout "Enter a grade: ";
cin grade;
while (grade >= 0 )
{
total = total + grade;
cout "Enter a grade: ";
cin grade;
}
cout "\nThe total of the grades is " total endl;
return 0;
}
The following is a sample run of the above program:
To stop entering grades, type in any number less than 0.
Enter a grade: 95
Enter a grade: 100
Enter a grade: 82
Enter a grade: -2
The total of the grades is 277
2.5.7 Example
#include <iostream.h>
int main()
{
int sum = 0;
for (int number = 2; number <= 100; number += 2)
1. 1102.50
2. 1157.62
3. 1215.51
4. 1276.28
5. 1340.10
6. 1407.10
7. 1477.46
8. 1551.33
9. 1628.89
2.5.9 Example
#include <iostream.h>
int main()
{
const int MAXI = 5;
const int MAXJ = 4;
int i, j;
for(i = 1; i <= MAXI; i++) // start of outer loop
{
cout "\ni is now " i endl;
Here, a request for a new id-number is repeated until a valid number is entered.
do {
cout \nEnter an identification number:;
cin idNum;
if (idNum < 1000 || idNum > 1999)
{
cout An invalid number was just entered\n;
cout Please reenter an ID number /n;
}
else break;
} while (true);
• sequence structure
• selection structure
• repetition structure
The sequence structure is built into C++. Unless directed otherwise, the computer executes C++ statements
one after the other in the order in which they are written. Below is a sequence structure.
// initialization phase
total = 0;
gradeCounter = 0;
// processing phase
cout "Enter grade, -1 to end: ";
cin grade;
while ( grade != -1 ) {
total = total + grade;
gradeCounter = gradeCounter + 1;
cout "Enter grade, -1 to end: ";
cin grade;
}
// termination phase
if ( gradeCounter != 0 ) {
average = double ( total ) / gradeCounter;
2.5.12 Arrays
An array is an advanced data type that contains a set of data represented by a single variable name.
An element is an individual piece of data contained in an array.
2.5.13 Example
#include <iostream.h>
int main(){
char StudentGrade[5]= {`A', `B', `C', `D', `F'};
for ( int i = 0; i < 5; i++)
cout StudentGrade[i] endl;
return 0;
}
The output is:
A
B
C
D
F
2.5.14 Example
// Compute the sum of the elements of the array
#include <iostream.h>
int main()
{
const int arraySize = 12;
int a[ arraySize ] = { 1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45 };
int total = 0;
The strcpy() function copies a literal string or the contents of a char variable into another char variable
using the syntax:
strcpy(destination, source);
where destination represents the char variable to which you want to assign a new value to and the
source variable represents a literal string or the char variable contains the string you want to assign to the
destination.
The strcat() function combines two strings using the syntax:
strcat(destination, source);
where destination represents the char variable whose string you want to combine with another string.
When you execute strcat(), the string represented by the source argument is appended to the string contained
in the destination variable.
Example:
char FirstName[25];
char LastName[25];
char FullName[50];
strcpy(FirstName, Mike);
strcpy(LastName, Thomson);
strcpy(FullName, FirstName);
strcat(FullName, );
strcat(FullName, LastName);
Two strings may be compared for equality using the strcmp() function. When two strings are compared,
their individual characters are compared a pair at a time. If no dierences are found, the strings are equal;
if a dierence is found, the string with the rst lower character is considered the smaller string.
The functions listed in Figure 2 are contained in the string.h header le. To use the functions, you must
add the statement #include<string.h> to your program.
2.5.15.2 Example
#include<iostream.h>
#include<string.h>
int main()
{
char FirstName[25];
2.5.16 Structures
A structure, or struct, is an advanced, user-dened data type that uses a single variable name to store
multiple pieces of related information.
The individual pieces of information stored in a structure are referred to as elements, eld, or members.
You dene a structure using the syntax:
struct struct_name{
data_type field_name;
data_type field_name;
. . .. . ...
} variable_name;
For example, the statement
struct emloyee{
char idnum[5];
char name[40];
long salary;
};
declares the form of a structure named employee and reserves storage for the individual data items listed
in the structure. The employee structure consists of three data items or elds.
And the statement
struct emloyee{
char idnum[5];
char name[40];
long salary;
} Emp;
declares that Emp is a structure variable which has the form of the structure employee.
To access the eld inside a structure variable, you append a period to the variable name, followed by the
eld name using the syntax:
variable.field;
When you use a period to access a structure elds, the period is referred to as the member selection
operator.
2.5.17 Example
#include <iostream.h>
struct Date // this is a global declaration
{
int month;
int day;
int year;
};
int main()
{
Date birth;
birth.month = 12;
birth.day = 28;
birth.year = 1986;
cout "\nMy birth date is "
birth.month '/'
birth.day '/'
birth.year % 100 endl;
return 0;
}
The ouput of the above program is:
My birth date is 12/28/86
int main()
{
const int NUMRECS = 5;
// maximum number of records
int i;
PayRecord employee[NUMRECS] = {
{ 32479, "Abrams, B.", 6.72 },
{ 33623, "Bohm, P.", 7.54},
{ 34145, "Donaldson, S.", 5.56},
{ 35987, "Ernst, T.", 5.43 },
{ 36203, "Gwodz, K.", 8.72 }
};
Variable names that will be used in the function header line are called formal parameters.
2.6.1.3.1 Example
// Finding the maximum of three integers
#include <iostream.h>
int maximum(int, int, int); // function prototype
int main()
{
int a, b, c;
cout "Enter three integers: ";
cin a b c;
2.6.3 Example
// Using an inline function to calculate
// the volume of a cube.
#include <iostream.h>
inline double cube(double s) { return s * s * s; }
int main()
{
cout "Enter the side length of your cube: ";
double side;
cin side;
cout "Volume of cube with side "
side " is " cube(side) endl;
return 0;
}
The output of the above program:
Enter the side length of your cube: 3.5
Volume of cube with side 3.5 is 42.875
{
if( x < 0)
x = -x;
cout The absolute value of the integer is x endl;
}
void showabs(double x)
{
if( x < 0)
x = -x;
cout The absolute value of the double is x endl;
}
The function call
showabs(10);
causes the compiler to use the rst version of the function showabs.
The function call
showabs(6.28);
causes the compiler to use the second version of the function showabs.
2.6.4.1 Example:
#include <iostream.h>
int x; // create a global variable named firstnum
void valfun(); // function prototype (declaration)
int main()
{
int y; // create a local variable named secnum
x = 10; // store a value into the global variable
y = 20; // store a value into the local variable
2.6.5 Example
#include <iostream.h>
float number = 42.8; // a global variable named number
int main()
{
float number = 26.4; // a local variable named number
cout "The value of number is " number endl;
return 0;
}
The output of the above program:
The value of number is 26.4
2.6.5.1 Example
#include <iostream.h>
float number = 42.8; // a global variable named number
int main()
{
float number = 26.4; // a local variable named number
cout "The value of number is " ::number endl;
return 0;
}
The output of the above program:
The value of number is 42.8
2.6.6.1.2 Example
#include <iostream.h>
int funct(int); // function prototype
int main()
{
int count, value; // count is a local auto variable
for(count = 1; count <= 10; count++)
value = funct(count);
cout count `\t' value endl;
return 0;
}
Note:
1. The initialization of static variables is done only once when the program is rst compiled. At compile
time, the variable is created and any initialization value is placed in it. Thereafter, the value in the
variable is kept without further initialization each time is called. (compile-time initialization).
2. All static variables are set to zero when no explicit initialization is given.
//file2
double b;
int func3();
{
.
.
}
int func4();
{
.
.
}
//end of file2
Although the variable a has been declared in le1, we want to use it in le2. Placing the statement extern
int a in le2, we can extend the scope of the variable a into le2.
Now the scope of the variable a is not only in le1, but also in func3 and func4.
//file1
int a;
float c;
static double d;
.
.
int main()
{
func1();
func2();
func3();
func4();
.
}
extern double b;
int func1();
{
.
.
}
int func2();
{
.
.
}
//end of file1
//file2
double b;
extern int a;
int func3();
{
.
.
}
int func4();
{
extern float c;
.
.
}
//end of file2
Besides, placing the statement extern oat c; in func4() extends the scope of this global variable, created
in le1, into func4(), and the scope of the global variable b, created in le2, is extended into func1() and
func2() by the declaration statement extern double b; placed before func1().
Note:
int main()
{
int x = 2, z = 4;
cout "x = " x " before squareByValue\n"
"Value returned by squareByValue: "
squareByValue( x ) endl
"x = " x " after squareByValue\n" endl;
cout "z = " z " before squareByReference" endl;
squareByReference( z );
cout "z = " z " after squareByReference" endl;
return 0;
}
int squareByValue( int a )
{
return a *= a; // caller's argument not modified
2.6.8 Recursion
In C++, it's possible for a function to call itself. Functions that do so are called seft-referential or recursive
functions.
Example: To compute factorial of an integer
1! = 1
n! = n*(n-1)!
Example
// Recursive factorial function
#include <iostream.h>
#include <iomanip.h>
unsigned long factorial( unsigned long );
int main()
{
for ( int i = 0; i <= 10; i++ )
cout setw( 2 ) i "! = " factorial( i ) endl;
return 0;
}
// Recursive definition of function factorial
unsigned long factorial( unsigned long number )
{
if (number < 1) // base case
return 1;
else // recursive case
return number * factorial( number - 1 );
}
The output of the above program:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
Figure 2.37: The data area for the rst call to factorial
The progress of execution for the recursive function factorial applied with n = 3 is as follows:
During the execution of the function call factorial(3), the memory stack evolves as shown in the gure
below. Whenever the recursive function calls itself, a new data area is pushed on top of the stack for that
function call. When the execution of the recursive function at a given level is nished, the corresponding
data area is popped from the stack and the return value is passed back to its calling function.
Figure 2.39: The memory stack for execution of function call factorial(3)
1. Read in the amount to be deposited in the bank, the interest rate and the number of years to deposit.
2. Invoke the function to compute a table which keeps the amount we get after i years of deposit at the
i-th component of the array.
2.6.10 Pointers
In this section, we discuss one of the most powerful features of the C++ programming language, the pointer.
Pointers are among C++'s most dierent capabilities to master. In section Pass by Reference, we saw that
references can be used to perform call-by-reference. Pointers enable programs to simulate call-by-reference
and to create and manipulate dynamic data structures (i.e., data structures that can grow and shrink).
A pointer is a special type of variable that stores the memory address of other variables.
You declare a variable as a pointer by placing the indirection operator (*) after the data type or before
the variable name.
Examples:
int *pFirstPtr;
int *pSecondPtr;
You use the address-of operator (&) to assign to the pointer variable the memory address of another
variable.
Examples:
double dPrimeInterest;
double *pPrimeInterest;
pPrimeInterest = &dPrimeInterest;
Once you assign the memory address of a variable to a pointer, to access or modify the contents of the
variable pointed to by the pointer, you precede a pointer name in an expression with the de-reference (*)
operator.
Example
The program in this example demonstrates the pointer operators. Memory locations are output in this
example as hexadecimal integers.
#include<iostream.h>
int main()
{
int a;
int *aPtr; // aPtr is a pointer to an integer
a = 7;
aPtr = &a; //aPtr set to address of a
cout The address of a is &a
\nThe value of aPtr is aPtr;
cout \n\nThe value of a is a
\nThe value of *aPtr is *aPtr
endl;
return 0;
}
The output of the above program:
The address of a is 0x0065FDF4
The value of aPtr is 0x0065FDF4
The value of a is 7
The value of *aPtr is 7
Notice that the address of a and the value of aPtr are identical in the output, conrming that the address
of a is assigned to the pointer variable aPtr.
A string may be assigned in a declaration to either a character array or a variable of type char *. The
declarations
char color[] = blue;
char* colorPtr = blue;
each initialize a variable to the string blue. The rst declaration creates a 5-element array color con-
taining the characters `b', `l', `u', `e' and `\0'. The second declaration creates pointer variable colorPtr that
points to the string blue somewhere in the memory.
The rst declaration determines the size of the array automatically based on the number of initializers
provided in the initializer list.
Example
/* Printing a string one character at a time using a non-constant pointer to constant
data */
#include<iostream.h>
int main( )
{
char strng[] = Adams;
char *sPtr;
sPtr = &strng[0];
cout \nThe string is: \n;
for( ; *sPtr != `\0'; sPtr++)
cout *sPtr ` `;
return 0;
}
The output of the above program:
The string is:
A d a m s
Note: The name of a string by itself is equivalent to the base address of that string.
2.7.1 Classes
In C++ programming, classes are structures that contain variables along with functions for manipulating
that data.
The functions and variables dened in a class are referred to as class members.
Class variables are referred to as data members, while class functions are referred to as member
functions.
Classes are referred to as user-dened data types or programmer-dened data types because you can
work with a class as a single unit, or objects, in the same way you work with variables.
When you declare an object from a class, you are said to be instantiating an object.
The most important feature of C++ programming is class denition with the class keyword. You dene
classes the same way you dene structures, and you access a class's data members using the member
selection operator.
Example:
class Time {
public:
Time();
void setTime( int, int, int );
void printMilitary();
void printStandard();
private:
int hour;
int minute;
int second;
};
Once the class has been dened, it can be used as a type in object, array and pointer denitions as
follows:
7 This content is available online at <http://cnx.org/content/m27275/1.1/>.
The class name becomes a new type specier. There may be many objects of a class, just as there may
be many variables of a type such as int. The programmer can create new class types as needed. This is one
reason why C++ is said to be an extensible language.
The diagram shown above follows the format of the Unied Modeling Language (UML). Each class is
represented by a box, with the class name in the top portion of the box, any data members that you care
to describe in the middle portion of the box, and the member functions (the functions that belong to this
object, which receive any messages you send to that object) in the bottom portion of the box.
double dPurchasePricePerShare;
double dCurrentPricePerShare;
};
#include <iostream.h>
void Time::printMilitary()
{
cout ( hour < 10 ? "0" : "" ) hour ":"
( minute < 10 ? "0" : "" ) minute;
}
void Time::printStandard()
{
cout ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
":" ( minute < 10 ? "0" : "" ) minute
":" ( second < 10 ? "0" : "" ) second
( hour < 12 ? " AM" : " PM" );
}
// implementation section
int main()
{
Date a; // declare an object
Date b; // declare an object
Date c(4,1,2002); // declare an object
return 0;
}
delete pPrimeInterest;
*pPimeInterest = 0.070;
cout The value of pPrimeInterest is:
*pPrimeInterest endl;
cout The memory address of pPrimeInterest is:
&pPrimeInterest endl;
return 0;
}
The output of the above program:
The value of pPrimeInterest is: 0.065
The memory address of pPrimeInterest is: 0x0066FD74
The value of pPrimeInterest is: 0.070
The memory address of pPrimeInterest is: 0x0066FD74.
Note: The above program declares the pPrimeInterest pointer on the heap and assigns to it a value of
0.065. Then the delete operator deletes the heap address that stores the value of 0.065. Finally, a new
value is added to the heap address. You can see that after the delete statement executes, the pPimeInterest
pointer still point to the same memory address.
Example
In the following program, we can create some objects of the class Stocks on the stack or on the heap and
then manipulate them.
#include<iostream.h>
class Stocks{
public:
int iNumShares;
double dPurchasePricePerShare;
double dCurrentPricePerShare;
};
double totalValue(Stocks* pCurStock){
double dTotalValue;
dTotalValue = pCurStock->dCurrentPricePerShar*pCurStock->iNumShares;
return dTotalValue;
}
int main( ){
//allocated on the stack with a pointer to the stack object
Stocks stockPick;
Stocks* pStackStock = &stockPick;
pStackStock->iNumShares = 500;
pStackStock-> dPurchasePricePerShare = 10.785;
pStackStock-> dCurrentPricePerShare = 6.5;
cout totalValue(pStackStock) endl;
//allocated on the heap
Stocks* pHeapStock = new Stocks;
pHeapStock->iNumShares = 200;
pHeapStock-> dPurchasePricePerShare = 32.5;
pHeapStock-> dCurrentPricePerShare = 48.25;
cout totalValue(pHeapStock) endl;
return 0;
}
The output of the above program:
3250
9650
// class declaration
class Book
{
private:
char *title; // a pointer to a book title
public:
Book(char * = NULL); // constructor with a default value
void showtitle(); // display the title
};
// class implementation
Book::Book(char *strng)
{
title = new char[strlen(strng)+1]; // allocate memory
strcpy(title,strng); // store the string
}
void Book::showtitle()
{
cout title endl;
return;
}
int main()
{
Book book1("DOS Primer"); // create 1st title
Book book2("A Brief History of Western Civilization"); // 2nd title
return 0;
}
The output of the above program:
DOS Primer
A Brief History of Western Civilization
The body of the Book() constructor contains two statements. The rst statement performs two taks:
First, the statement allocates enough storage for the length of the name parameter plus one to accommodate
the end-of-string null character, `\n'. Next, the address of the rst allocated character position is assigned
to the pointer variable title.
//class declaration
class Elevator
{
private:
int currentFloor;
public:
Elevator(int = 1); //constructor
void request(int);
};
// implementation section
Elevator::Elevator(int cfloor)
{
currentFloor = cfloor;
}
void Elevator::request(int newfloor)
{
if (newfloor < 1 || newfloor > MAXFLOOR || newfloor == currentFloor)
; // doing nothing
else if (newfloor > currentFloor) // move elevator up
{
cout \nStarting at floor currentFloor endl;
while (newfloor > currentFloor)
{
currentFloor++;
cout Going up now at floor currentFloor endl;
}
cout Stopping at floor currentFloor endl;
}
else // move elevator down
{
cout \nStarting at floor currentFloor endl;
while (newfloor < currentFloor)
{
currentFloor;
cout Going down now at floor currentFloor endl;
}
cout Stopping at floor currentFloor endl;
}
return;
}
int main()
{
Elevator a; // declare 1 object of type Elevator
a.request(6);
a.request(3);
return 0;
}
Note that control is provided by the main() function. This control is sequential, with two calls made
to the same object operation, using dierent argument values. This control is perfectly correct for testing
purposes. However, by incorporating calls to request() within a while loop and using the random number
function rand() to generate random oor requests, a continuous simulation of the elevator's operation is
possible.
2.8.2 Destructors
A default destructor cleans up any resources allocated to an object once the object is destroyed. The
default constructor is sucient for most classes, except when you have allocated memory on the heap.
To delete any heap variables declared by your class, you must write your own destructor function.
You create a destructor function using the name of the class, the same as a constructor function, preceded
by a tilde ∼. Destructor functions cannot be overloaded. A destructor accepts no parameter and returns no
value.
A destructor is called in two ways:
- when a stack object loses scope when the function in which it is declared ends.
- when a heap object is destroyed with the delete operator.
The destructor itself does not actually destroy the object it performs termination house keeping before
the system reclaims the object's memory so that memory may be reused to hold new objects.
Example
//Stocks_02.h
class Stocks {
public:
Stocks(char* szName);
∼Stocks(); //destructor
void setStockName(char* szName);
char* getStockName();
void setNumShares(int);
2.8.4 Inheritance
Inheritance is a form of software reusability in which new classes are created from existing classes by
absorbing their attributes and behaviors, and overriding or embellishing these with capabilities the new
classes require. Software reusability saves time in programming development. It encourages the reuse of
proven and debugged high quality software, thus reducing problems after a system becomes functional.
• constructor functions
• copy constructor functions
• destructor functions
• overloaded assignment (=) functions
return 0;
}
The object cust which belongs to the class Customer can call the member functions setFields() and
outputData() that belongs to the base class Person.
Example
#include<iostream.h>
#include<string.h>
class Person
{
private:
int idnum;
char lastName[20];
char firstName[15];
public:
void setFields(int, char[], char[]);
void outputData( );
};
void Person::setFields(int num, char last[], char first[])
{
idnum = num;
strcpy(lastName, last);
strcpy(firstName, first);
}
void Person::outputData( )
{
cout ID# idnum Name: firstName lastName endl;
}
class Customer:public Person
{
private:
double balanceDue;
public:
void setBalDue;
void outputBalDue( );
};
void Customer::setBalDue(double bal)
{
balanceDue = bal;
}
void Customer::outputBalDue()
{
cout Balance due $ balanceDue endl;
}
int main()
{
Customer cust;
cust.setFields(215, Santini, Linda);
cust.outputData();
cust.setBalDue(147.95);
cust.outputBalDue();
return 0;
}
The output of the above program:
ID#215 Name: Linda Santini
Balance due $147.95
Of course, a Customer object can use its own class' member functions, setBalDue() and outputBalDue().
Additionally, it can use the Person functions, setFields() and outputData(), as if they were its own.
Each class in a class hierarchy cumulatively inherits the class members of all classes that precede it in
the hierarchy chain.
A class that directly precedes another class in a class hierarchy, and is included in the derived class's
base list, is called the direct base class.
A class that does not directly precede another class in a class hierarchy, and that not included in the
derived class's base list, is called the indirect base class.
The following code shows a modied version of the Person class declaration in which the private access
modier has been changed to protected.
Example:
class Person {
protected:
int idNum;
char lastName[20];
char firstName[15];
public:
void setFields(int num, char last[], char first[]);
void outputData();
};
A member function in Customer class that attempts to directly access to the idNum data member will
work correctly since the Customer class is a derived class of the Person class and the idNum data member
is now declared as protected.
int idnum;
char lastName[20];
char firstName[15];
public:
void setFields(int, char[], char[]);
void outputData( );
};
void Person::setFields(int num, char last[], char first[])
{
idnum = num;
strcpy(lastName, last);
strcpy(firstName, first);
}
void Person::outputData( )
{
cout ID# idnum Name: firstName lastName endl;
}
// derived class
class Employee:public Person
{
private:
int dept;
double hourlyRate;
public:
void setFields(int, char[], char[], int, double);
};
void Employee::setFields(int num, char last[], char first[], int dept, double sal)
{
Person::setFields(num, last, first);
dept = dep;
hourlyRate = sal;
}
int main()
{
Person aPerson;
aPerson.setFields(123, Kroening, Ginny);
aPerson.outputData();
cout endlendl;
Employee worker;
worker.Person::setFields(777,John, Smith);
worket.outputData();
worker.setFields(987,Lewis, Kathy, 6, 23.55);
worker.outputData();
return 0;
}
The output of the above program:
ID # 123 Name: Ginny Kroening
ID # 777 Name: John Smith
ID # 987 Name: Kathy Lewis
During the instantiating process, the base class portion of the object is instantiated, and then the derived
class portion of the object is instantiated.
So, two constructors execute for a single derived class object: the base class constructor and the derived
class constructor.
When a derived class object instantiates, constructors begin executing at the top of the class hierarchy.
First, the base constructor executes, then any indirect base class's constructors execute. Finally, the derived
class' constructor executes.
When an object is destroyed, class destructors are executed in the reverse order. First, the derived class's
destructor is called, then the destructors for any indirect base classes, and nally, the destructor for the base
class. Figure below illustrates this process using a class hierarchy with four levels.
The order of construction makes sense, since it allows base classes to perform any initialization on class
members that may be used by derived classes. And the order of destruction ensures that any base class
members required by derived classes are not destroyed until all objects of any derived classes are destroyed
rst.
Example
#include<iostream.h>
#include<string.h>
class Person
{
private:
int idnum;
char lastName[20];
char firstName[15];
public:
Person();
void setFields(int, char[], char[]);
void outputData( );
};
Person::Person(){
cout Base class constructor call endl;
}
Attributions
Collection: PROGRAMMING FUNDAMENTALS IN C++
Edited by: Dr Duong Tuan Anh
URL: http://cnx.org/content/col10788/1.1/
License: http://creativecommons.org/licenses/by/3.0/
Module: "Syllabus"
By: Dr Duong Tuan Anh
URL: http://cnx.org/content/m27299/1.1/
Pages: 1-10
Copyright: Dr Duong Tuan Anh
License: http://creativecommons.org/licenses/by/3.0/
Module: "Exercises"
By: Dr Duong Tuan Anh
URL: http://cnx.org/content/m27239/1.1/
Pages: 10-24
Copyright: Dr Duong Tuan Anh
License: http://creativecommons.org/licenses/by/3.0/
Module: "Assignments"
By: Dr Duong Tuan Anh
URL: http://cnx.org/content/m27202/1.1/
Pages: 24-30
Copyright: Dr Duong Tuan Anh
License: http://creativecommons.org/licenses/by/3.0/
Module: "Labworks"
By: Dr Duong Tuan Anh
URL: http://cnx.org/content/m27278/1.1/
Pages: 31-56
Copyright: Dr Duong Tuan Anh
License: http://creativecommons.org/licenses/by/3.0/
About Connexions
Since 1999, Connexions has been pioneering a global system where anyone can create course materials and
make them fully accessible and easily reusable free of charge. We are a Web-based authoring, teaching and
learning environment open to anyone interested in education, including students, teachers, professors and
lifelong learners. We connect ideas and facilitate educational communities.
Connexions's modular, interactive courses are in use worldwide by universities, community colleges, K-12
schools, distance learners, and lifelong learners. Connexions materials are in many languages, including
English, Spanish, Chinese, Japanese, Italian, Vietnamese, French, Portuguese, and Thai. Connexions is part
of an exciting new information distribution system that allows for Print on Demand Books. Connexions
has partnered with innovative on-demand publisher QOOP to accelerate the delivery of printed course
materials and textbooks into classrooms worldwide at lower prices than traditional academic publishers.