You are here: Home » Content » Labworks
Quality
Affiliated with  (?)
This content is either by members of the organizations listed or about topics related to the organizations listed. Click each link to see a list of all content affiliated with the organization.
Lenses
Tags  (?)
These tags come from the endorsement, affiliation, and other lenses that include this content.

Labworks

Module by: Dr. Duong Tuan Anh

TABLE OF CONTENTS

Lab Session 1:
Introduction to C++
Lab Session 2:
Selection Structures
Lab Session 3:
Repetition Structures
Lab Session 4:
Arrays
Lab Session 5:
Structures
Lab Session 6:
Functions
Lab Session 7:
Pointers
Lab Session 8:
Introduction to Classes
Lab Session 9:
Object Manipulation
Lab Session 10:
Inheritance
Programming Project Topic Examples

LAB SESSION 1: INTRODUCTION TO C++

1. OBJECTIVE

The objectives of Lab 1 are (1) to known how to run a simple C++ program; (2) to know the basic data types and operators; (3) to learn how to use variable declarations and assignment statements.

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. Run the above program
  2. Use #define to define the constant PI
  3. Declare the constant PI in the file “mydef.h”, and then use the #include directive to insert the header file in the above program.
2.2) Debug the following code segment.
#include <iostream.h>
int main()
{
const int age=35;
cout << age << “\n”;
age = 52;
cout << age << “\n”;
return 0;
}
2.3) What is the result of each following expression:
  1. 1 + 2 * 4 / 2
  2. (1 + 2) * 4 / 2
  3. 1 + 2 * (4 / 2)
  4. 9 % 2 + 1
  5. (1 + (10 - (2 + 2)))
2.4) Run the following programs and explain their results.
a.
void main()
{
short i = -3;
unsigned short u;
cout<< sizeof(i)<< &i;
cout<<sizeof(u)<<&u;
cout << (u = i) << "\n";
}
b.
void main()
{
byte i = 125*4/10;
cout << i << "\n";
}
2.5) Write a program that inputs two time points and display the difference between them.
2.6) Run the following programs and explain their results:
a.
#include <iostream.h>
int main()
{
int f, g;
g = 5;
f = 8;
if ((g = 25) || (f = 35))
cout << “g is “ << g << “ and f got changed to “ << f;
return 0;
}
b.
#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

LAB SESSION 2: SELECTION STRUCTURES

1. OBJECTIVE

The objective of Lab 2 is to practice C++’s selection structures, such as:
  • if
  • if … else
  • switch

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 “;
cin >> num;
if (num == 1)
{ BEEP; }
else if (num == 2)
{ BEEP; BEEP; }
else if (num == 3)
{ BEEP; BEEP; BEEP; }
else if (num == 4)
{ BEEP; BEEP; BEEP; BEEP; }
else if (num == 5)
{ BEEP; BEEP; BEEP; BEEP; BEEP; }
return 0;
}
2.2) Run the following program:
#include <iostream.h>
#define BEEP cout << “\a \n”
int main()
{
int num;
cout << “Please enter a number “;
cin >> num;
switch (num)
{
case (1): { BEEP;
break; }
case (2): { BEEP; BEEP;
break; }
case (3): { BEEP; BEEP; BEEP;
break; }
case (4): { BEEP; BEEP; BEEP; BEEP;
break; }
case (5): { BEEP; BEEP; BEEP; BEEP; BEEP;
break; }
}
return 0;
}
2.3) Remove the break statements from the above program and then try it again and explain the result.
2.4) Use switch statement to rewrite the following code segment:
if (num == 1)
{cout << “Alpha”; }
else if (num == 2)
{ cout << “Beta”; }
else if (num == 3)
{ cout << “Gamma”; }
else
{ cout << “Other”; }
2.5) Write a program that inputs the integer variable n consisting of 3 digits and displays it in ascending order of digits.
Example: n = 291. It should be displayed as 129.
2.6) Write a program that inputs a date with correct month, year and day components, and then checks if the year is a leap year or not. Show the result on the screen.
2.7) Write a program that can calculate the fee for a taxi ride. The formula is as follows:
  • The first kilometer costs 5000.
  • Each next 200m costs 1000.
  • If the distance is more than 30km then each next kilometer adds 3000 to the fee.
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.

LAB SESSION 3: REPETITION STRUCTURES

1. OBJECTIVE

The objectives of Lab 3 are to practice the C++’s repetition structures, such as:
  • for
  • while
  • do…while

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 ++;
} // Add to count.
} while (grade >= 0.0); // Quit when -1 entered.
grade_avg = (total_grade / grade_ctr);
cout << “\nYou made a total of “ << setprecision(1) <<
total_grade << “ points.\n”;
cout << “Your average was “ << grade_avg << “\n”;
if (total_grade >= 450.0)
cout << “** You made an A!!”;
return 0;
}
2.3) Test the following program:
#include <iostream.h>
void main()
{
int outer, num, fact, total;
cout << “What factorial do you want to see? “;
cin >> num;
for (outer=1; outer <= num; outer++)
{
total = 1;
for (fact=1; fact<= outer; fact++)
{ total *= fact; }
}
cout << “The factorial for “ << num << “ is “ << total;
return 0;
}
2.4) Determine the result of each following code segment:
a.
for (ctr=10; ctr>=1; ctr-=3)
{ cout << ctr << “\n”; }
b.
n =10;
i=1;
for (i = 0 ; i < n ; i++)
cout<< ++i<<endl;
c.
for (i=1; i<=10; i++);
for (j=1; j<=5; j++)
{
if ( i == j )
continue;
else ( i>j)
break;
else
cout << i << j;
cout<< endl;
}
d.
i=1;
start=1;
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 2
Fahrenheit = (9.0 / 5.0) * Celsius + 32.0;
2.6) Write a C++ program to compute the sum and average of N single-precision floating point numbers entered by the user. The value of N is also entered by the user.
2.7) The value of Euler constant, e, is approximated by the following series:
e = 1 + 1/1! +1/2! + 1/3! + 1/4! + 1/5! + …
Using this series, write a C++ program to compute e approximately. Use while structure that terminates when the difference between two successive approximations becomes less than 1.0E-6.
2.8) Write a C++ program to calculate and display the amount of money accumulated in a saving bank account at the end of each year for 10 years when depositing 1000$ in the bank. The program has to display the amount of money when interest rates change from 6% to 12% with the increment 1%. Thus, you should use two nested loops: the outer loop iterates according to interest rates and the inner loop iterates according to the years.
2.9) Write a C++ program that inputs a positive integer n and lists out n first prime numbers.
2.10) Write a C++ program to display an equilateral triangle with the height h (h is entered from the user). Example: h = 4
Figure 3

LAB SESSION 4: ARRAYS

1. OBJECTIVE

The objective of Lab session 4 is to get familiar with arrays, one-dimensional and two-dimensional arrays.

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 floating point numbers and finds 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 finds 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 first 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 find 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 4
After transposing it, it becomes as follows:
Figure 5
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.

LAB SESSION 5: STRINGS AND STRUCTURES

1. OBJECTIVE

The objectives of Lab session 5 are (1) to get familiar with strings; (2) to get familiar with structures; (3) to practice on processing arrays of structures.

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;
};
define 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 6
b. Using the data type defined 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.

LAB SESSION 6: FUNCTIONS

1. OBJECTIVE

The objectives of Lab session 6 is to practice on C++ functions.

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 find the average of all the elements in a double precision floating point array that is passed to the function as a parameter.
b. Write a C++ program that inputs a double precision floating point array and invokes the above function to find 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 7
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 find 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
  1. Write a recursive function to compute C(n,m).
  2. Write a complete C++ program that reads two integers N and M and invokes the function to compute C(N,M) and prints the result out.
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) ;
}
a. First write a C++ program to test the function.
b. Write and test an equivalent iterative function.

LAB SESSION 7: POINTERS

1. OBJECTIVE

The objectives of Lab session 7 are to get familiar with how to use pointers in C++.

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;
cout<<sizeof(a)<<endl;
cout<<sizeof(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];
c. ara = 15;
d. *(ip2 + 2) = 15; // Assuming ip2 and ara are equal.
2.5) Run the following program and explain the output.
#include <iostream.h>
void swap(int a[], int *c1, int *c2, int *d1, int *d2);
void main()
{
int a[2], c1, c2,d1,d2;
int *x1, *x2, *y1, *y2;
a[0] = 1 ; a[1] =2;
c1 = 1; c2 =2;
d1 = 1; d2 =2;
x1 = &c1; x2 = &c2;
y1 = &d1; y2 = &d2;
swap(a, x1,x2,y1,y2);
cout<<a[0]<<a[1]<<” “
<< *x1<<*x2<<” ”
<<*y1<<*y2;
swap(a, x1,x2,y1,y2);
cout<<a[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 find 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 find 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.

LAB SESSION 8: INTRODUCTION TO CLASSES

1. OBJECTIVE

The objectives of Lab session 8 are (1) to get familiar with how to define object classes; (2) to practice to write constructors and (3) to learn how to dynamically allocate/deallocate memory on the heap.

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;
float height;
float weight;
public:
void getinfo();
void disinfo();
};
void student::getinfo()
{
cout << " Roll no :";
cin >> rollno;
cout << " Age :";
cin >> age;
cout << " Sex:";
cin >> sex;
cout << " Height :";
cin >> height;
cout << " Weight :";
cin >> weight;
}
void student::disinfo()
{
cout<<endl;
cout<< " Roll no = "<< rollno << endl;
cout<< " Age =" << age << endl;
cout<< " Sex =" << sex << endl;
cout<< " Height =" << height << endl;
cout<< " Weight =" << weight << endl;
}
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 file and an implementation file and then run the program.
2.2) Given the class student as defined 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 defined in 2.1.a. Write a complete C++ program in which the main() function performs the following tasks:
  • to declare a run-time-allocated array on the heap to contain the student objects.
  • to prompt the user to enter an integer n and allocate a memory area on the heap to store n student objects.
  • to prompt the user to enter the student objects and store them in the array and display all the objects on the screen.
  • to deallocate the memory area for the array on the heap.
2.4) Test the following program:
class Int{
private:
int idata;
public:
Int(){
idata=0;
cout<<"default constructor is called"<<endl;
}
Int(int d){
idata=d;
cout<<"constructor with argument is called"<<endl;
}
void showData(){
cout<<"value of idata: "<<idata<<endl;
}
};
void main()
{
Int i;
Int j(8);
Int k=10;
Int *ptrInt = new Int();
ptrInt->showData();
delete ptrInt;
}
What are the outputs of the program? Explain the results.
What is the purpose of the statement delete ptrInt; in the program?
2.5) Define a class named Rectangle which contains two single-precision floating point data members: length and width. The class has some member functions:
  • A constructor with no parameters that assigns 0 to two data members of the created object.
  • A constructor with two single-precision floating-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) Define a class named CStudent which consists of the following data members:
  • Student id-number (integer).
  • An array of size 5 to contains at most 5 grades (single-precision floating point numbers).
  • An integer to indicate the number of entered grades.
The class also has the following member functions:
  • the constructor which assigns the initial values 0 to all data members of each Cstudent objects.
  • A function to get a student-id-number.
  • A function to get one grade and update the total of the entered grades.
  • A function to compute the average of all entered grades of a student.
  • A function to display student-id-number, and the average grade of that student.Include the class CStudent in a complete C++ program. This program creates one CStudent object, inputs the data for the object and displays the object’s data to verify the workings of the member functions.
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: ”
cin>>num;
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 first IntArray element only. The definition 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 findMax 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 first element and the largest element of the array.

LAB SESSION 9: OBJECT MANIPULATION

1. OBJECTIVE

The objectives of Lab session 9 are (1) to learn to write parameterized constructor, constructor with default arguments and (2) to practice destructors.

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: "<<idata<<endl;
}
};
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 modified program.
2.2) Run the following program in a C++ environment.
class Vector{
private:
int *value;
int dimension;
public:
Vector(int d=0){
dimension=d;
if (dimension==0)
value=NULL;
else{
value=new int[dimension];
for (int i=0; i<dimension; i++)
value[i]=0;
}
}
void showdata(){
for (int i=0; i<dimension; i++)
cout<<value[i];
cout<<endl;
}
~Vector(){
if (value!=NULL)
delete 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 definition.
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.
b. Test the following program in Visual C++ environment:
class some{ // code segment b
int *ptr;
public:
some(){
ptr= new int;
}
~some(){
cout<<"some's destructor"<<endl;
if (ptr!=NULL){
cout<<"delete heap memory"<<endl;
delete ptr;
}
}
};
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 definition 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 .
c. Run all the modifications in a C++ environment.

LAB SESSION 10: INHERITANCE

1. OBJECTIVE

The objectives of Lab session 10 are (1) to get familiar with class inheritance; (2) to learn the workings of the constructor and destructor of a derived class.
This lab session will use the inheritance hierarchies in the following figure.
Figure 8

2. EXPERIMENT

2.1) Given the Point class defined 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 defined 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 specifier of each of these members.
Derive from the class Point, another class named Point_Derive2 class, which is defined 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 specifier of each of these members.
Derive from the class Point, another class named Point_Derive3 class, which is defined 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 specifier 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();
};
// implementation section for Circle
// constructor
Circle::Circle(double r)
{
radius = r;
}
// calculate the area of a circle
double Circle::calcval()
{
return(PI * radius * radius);
}
// class declaration for the derived class
// Cylinder which is derived from Circle
class Cylinder : public Circle
{
protected:
double length; // add one additional data member and
public: // two additional function members
Cylinder(double r = 1.0, double l = 1.0) : Circle(r), length(l) {}
double calcval();
};
// implementation section for Cylinder
double Cylinder::calcval() // this calculates a volume
{
return length * Circle::calcval(); // note the base function call
}
int main()
{
Circle circle_1, circle_2(2); // create two Circle objects
Cylinder cylinder_1(3,4); // create one Cylinder object
cout << "The area of circle_1 is " << circle_1.calcval() << endl;
cout << "The area of circle_2 is " << circle_2.calcval() << endl;
cout << "The volume of cylinder_1 is " << cylinder_1.calcval() << endl;
circle_1 = cylinder_1; // assign a cylinder to a Circle
cout << "\nThe area of circle_1 is now " << circle_1.calcval() << endl;
return 0;
}
a. Run the program in a Visual C++ environment and determine the output of the program.
b. Modify the above program by deriving a subclass named Sphere from the base class Circle. Member functions of Sphere class include a constructor and a function named calcval() which returns the volume of the sphere. (The formula to compute the volume of a sphere is (4/3)*pi* R*R*R). And modify the main() function in order that it invokes all the member functions of the Sphere class.
2.3) Define a base class named Rectangle that contains two data members length and width. From this class, derive a subclass named Box which includes one more data member, depth. Two member functions of the base class are the constructor and a function named area() which returns the area of the rectangle. The derived class Box should have its own constructor and an overriding function area() which returns the surface area of the box and the function volume() that returns the volume of the box.
Write a complete C++ program which invokes all the member functions of the two above classes. Besides, the main() function also invokes the area() function of the base class to apply to a Box object. Explain the result of this function call.
2.4) a. Construct a class named CPoint that consists of the following data members and member functions:
  • 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:
  • There is one more data member: coordinate z.
  • There are overriding member functions in CPoint_3D for all corresponding member functions in the class CPoint.
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.

PROGRAMMING PROJECT TOPIC EXAMPLES

PROJECT 1

This project aims to review all the chapters from Chapter 1 (Introduction to Computers and Programming) to Chapter 6 (Functions and Pointers) which focus on structured programming.
An example of Project 1 can be described as follows:
The Colossus Airlines fleet consists of one plane with a seating capacity of 12. It makes one flight daily. Write a seating reservation program with the following features:
  • The program uses an array of 12 structures. Each structure should hold a seat identification 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 displays the following menu with six choices:
    • Show the number of empty seats
    • Show the list of empty seats.
    • Show the list of customers together with their seat numbers in the order of the seat numbers
    • Assign a customer to a seat
    • Remove a seat assignment
    • Quit
  • 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).

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:
  • Push: add an element to the top of the stack.
  • Pop: remove and return the top element of the stack.
  • Check if the stack is empty
  • 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.
For the moment, assume that we need to define 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 fixed 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).
  • Provide an integer data member to indicate the top of the stack.
As for the member functions of the stack class, we have to define 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 defining the stack class, write a main() function which does the following tasks:
  • Creating one stack object.
  • Pushing into the stack object ten integer elements which take values from 1 to 10 with the increment of 1.
  • Popping one by one element from the stack object and displaying it out, repeating this action until the stack becomes empty.
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)

Comments, questions, feedback, criticisms?

Send feedback