c++ Lab Exercises

11
All the students are required to compile the following programs and show the results (output) during the lab sessions, this is mandatory. WEEK -I 1. Write a program that reads in two integers and determines and prints if the first is a multiple of the second. 2. Write a program that inputs a five-digit integer, separates the integer into its individual digits and prints the digits separated from one another by three spaces each. 3. An integer number is said to be a perfect number if the sum of its factors, including 1 is equal to the number. Write a function perfect that determines whether parameter number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1 and 1000. Print the factors of each perfect number to confirm that the number is indeed perfect. 4. Approximation of π is calculated by formula Π= 4-4/3+4/5-4/7+4/9-4/11+…………….. Write a program to ask user how many terms he/she likes to use for approximation. Then print out a table that shows term number and approximation value from 1 to the term desired. WEEK II 1. Assume that you want to generate a table of multiples of any given number. Write a program that allows a user to enter the number and then generates the table, formatting it into 10 columns and 20 lines. Interaction with the program should look like this: Enter a number: 7

Transcript of c++ Lab Exercises

Page 1: c++ Lab Exercises

All the students are required to compile the following programs and show the results (output) during the lab sessions, this is mandatory.

WEEK -I

1. Write a program that reads in two integers and determines and prints if the first is a multiple of the second.

2. Write a program that inputs a five-digit integer, separates the integer into its individual digits and prints the digits separated from one another by three spaces each.

3. An integer number is said to be a perfect number if the sum of its factors, including 1 is equal to the number. Write a function perfect that determines whether parameter number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1 and 1000. Print the factors of each perfect number to confirm that the number is indeed perfect.

4. Approximation of π is calculated by formula Π= 4-4/3+4/5-4/7+4/9-4/11+……………..Write a program to ask user how many terms he/she likes to use for approximation. Then print out a table that shows term number and approximation value from 1 to the term desired.

WEEK II

1. Assume that you want to generate a table of multiples of any given number. Write a program that allows a user to enter the number and then generates the table, formatting it into 10 columns and 20 lines. Interaction with the program should look like this:Enter a number: 7

7 14 21 28 35 42 49 56 63 7077 84 91 98 105 112 119 126 133 140147 156 161 168 175 182 189 196 203 210

2. Write a program that displays a pyramid of Xs on the screen. The pyramid should look like this x xxx xxxxx xxxxxxx xxxxxxxxx

Page 2: c++ Lab Exercises

except that it should be 20 lines high, instead of the 5 lines shown here and also print the pyramid in the reverse manner.

3. A point on the two dimensional plane can be represented by two numbers: an X coordinate and a Y coordinate. For example, (4,5) represents a point 4 units to the right of the origin along the X axis and 5 units up the Y axis. The sum of two points can be defined as a new point whose X coordinate is the sum of the X coordinates of the points and whose Y coordinate is the sum of their Y coordinates. Write a program that uses a structure called point to model a point. Define three points, and have the user

input values to two of them. Than set the third point equal to the sum of the other two, and display the value of the new point. Interaction with the program might look like this:

Enter coordinates for P1: 3 4Enter coordinates for P2: 5 7Coordinates of P1 + P2 are : 8, 11

WEEK-III

1. Given that an EMPLOYEE class contains following members: Data Members: Employee_Number, Employee_Name, Basic, DA, Net_Salary. Data Functions: To read the data, To calculate Net_Salary and to print data members.Write a program to read the data of N employees and compute Net_Salary of each employee.

2. Create a class called TIME that has separate int member data for hours, minutes and seconds. One constructor should initialize this data to 0, and another should initialize it to fixed values. Another member function should add two objects of type time passed as arguments.A main() program should create two initialized time objects and one that isn’t initialized. Then it should add the two initialized values together, leaving the result in the third time variable. Finally it should display the value of this third variable. Make appropriate member functions const.

3. A hospital wants to create a database regarding its indoor patients. The information to store include

a) Name of the patientb) Date of admissionc) Diseased) Date of discharge

Create a structure to store the date (year, month and date as its members). Create a base class to store the above information. The member function should include functions to enter information and display a list of all the patients in the database. Create a derived class

Page 3: c++ Lab Exercises

to store the age of the patients. List the information about all to store the age of the patients. List the information about all the pediatric patients (less than twelve years in age).

4. Imagine a tollbooth at a bridge. Cars passing by the booth are expected to pay a 50 cent toll. Mostly they do, but sometimes a car goes by without paying. The tollbooth keeps track of the number of cars that have gone by, and of the total amount of money collected. Model this tollbooth with a class called tollbooth. The two data items are a type unsigned int to hold number of cars, and a type double to hold the total amount of money collected. A constructor initializes both of these to 0. A member function called payingCar() increments the car total and adds 0.50 to the cash total. Another function, called nopayCar(), increments the car total but adds nothing to the cash total. Finally, a member function called display() displays the two totals. Make appropriate member functions const.Include a program to test this class. This program should allow the user to push one key to count a paying car, and another to count a nonpaying car. Pushing the Esc key should cause the program to print out the total cars and total cash and then exit.

WEEK – IV

1. Raising a number n to a power p is the same as multiplying n by itself p times. Write a function called power( ) that takes a double value for n and an int value for p, and returns

the result as double value. Use a default argument of 2 for p, so that if this argument is omitted, the number will be squared. Write a main ( ) function that gets values from the user to test this function.

2. Create a class rational which represents a numerical value by two double values- NUMERATOR & DENOMINATOR.

Include the following public member functions:i. constructor with no arguments (default).ii.constructor with two arguments.iii. void reduce( ) that reduces the rational number by eliminating the highest common factor between the numerator and denominator.iv.Overload + operator to add two rational number.v.Overload >> operator to enable input through cin.vi.Overload << operator to enable output through cout.

Write a main() to test all the functions in the class.

WEEK – V

1. Write a function “no_repetitions()” which removes all repetitions of characters from a string. Test the function in a suitable main program, which should able to reproduce the given string and the string without repetitions.

Page 4: c++ Lab Exercises

2. Write a library of integer array functions with a header file “IntegerArray.h” and implementation file “IntegerArray.cpp”, which contains the following functions:

i. A function “input_array(a,n)” which allows the user to input values for the first n elements of the array a.

ii. A function “display_array(a,n)” which displays the values of the first n elements of the array a on the screen.

iii. A function “copy_array(a1,a2,n)” which copies the first n elements of a2 to the respective first n elements in a1.

iv. A function “standard_deviation(a,n)” which returns the standard deviation of the first n elements of a. Test the functions in a suitably defined main program.

WEEK – VI

1. Write a program to create a class called COMPLEX and implement the following overloading functions ADD that return a COMPLEX number.i. ADD(a,s2) – where a is an integer and s2 is a complex number.ii. ADD(s1,s2) – where s1 and s2 are complex numbers.

2. Write a program to create a class called OCTAL, which has the characteristics of an octal number. Implement the following operations by writing an appropriate constructor and an overloaded operator +.

i. OCTAL h=x; where x is an integerii. int y=h+k; where h is an OCTAL object and k is an integer.

Display the OCTAL result by overloading the operator <<. Also display the values of h and y.

3. Write a program to create a class called STRING and implement the following operations. Display the results after every operation by overloading the operator <<.

i. STRING s1=”IFHE” ii. STRING s2=”UNIVERSITY”iii. STRING s3=s1 + s2; (Use Copy Constructor).

4. Write a program to create a class called DATE. Accept two valid dates in the form dd/mm/yy. Implement the following operations by overloading the operators + and -. After every operation display the results by overloading the operator <<.

Page 5: c++ Lab Exercises

i. No_of_days=d1- d2; where d1 and d2 are DATE objects, d1>=d2 and no_of_days is an integer.

ii. d2=d1+ no_of_days; where d1 is a DATE object and no_of_days is an integer.

5. Write a program to create a class called MATRIX using a two-dimensional array of integers. Implement the following operations by overloading the operator == which checks the compatibility of two matrices m1 and m2 to be added and subtracted. Perform the addition and subtraction by overloading the operators + and – respectively. Display the results by overloading the operator <<.

WEEK VII

1. Imagine a publishing company that markets both book and audiocassette versions of its works. Create a class publication that stores the title and price of a publication. From this class derive two classes: book, which adds a page count and tape, which adds a playing time in minutes. Each of these three classes should have a getdata() function to get its data from the user at the keyboard, and a putdata() function to display its data.Write a main() program to test the book and tape classes by creating instances of them, asking the user to fill in data with getdata(), and then displaying the data with putdata().

2. Write a program to create a class called STUDENT with data members USN, Name and Age. Using inheritance, create the classes UGSTUDENT and PGSTUDENT having fields as Semester, Fees and Stipend. Enter the data for at least 5 students. Find the semester wise average age for all UG and PG students separately.

3. Make a class Employee with a name and salary. Make a class Manager inherit from Employee. Add an instance variable, named department, of type string. Supply a method to string that prints the manager s name, department and salary. Make a class Executive inherit from Manager. Supply a method to String that prints the string Executive followed by the information stored in the Manager super class object. Supply a test program that tests these classes and methods.

WEEK VIII

1. Write a program using pointers that reads a group of numbers from the user and places them in an array of type float. Once the numbers are stored in the array, the program should average them and print the result.

2. Write a program which accepts a string and print the string in reverse using pointers.

Page 6: c++ Lab Exercises

3. Write a program that inputs a string and prints the string backwards. Convert all uppercase characters to lowercase and vice-versa.

4. Write a Boolean valued function which returns “True” if its first string argument is alphabetically smaller than its second string argument, “False” otherwise. You may assume that the two strings contain only lower case letters, and no blanks or other non-alphabetic characters. Test your function with a suitable main program and convert the function to pointer arithmetic syntax, and check that it still behaves in the same way.

WEEK IX

1. Create a base class called shape. Use this class to store two double type values thatcould be used to compute the area of figures. Derive two specific classes called triangle and rectangle from the base shape. Add to the base class, a member function get_data ( ) to initialize base class data members and another member function display_area ( ) to

compute and display the area of figures. Make display_area ( ) as a virtual function and redefine this function in the derived classes to suit their requirements. Using these three classes, design a program that will accept dimensions of a triangle or a rectangle interactively and display the area.

2. Consider the following class definitionclass father { Protected: int age; public: father(int x) { age=x; }virtual void iam() { Cout<<I AM THE FATHER , MY AGE IS: <<age<<endl; }};Derive the two classes and daughter from the above class and for each, define iam() to write our similar but appropriate messages. You should also define suitable constructors for these classes. Now, write a main() that creates objects of the three classes and then calls iam() for them. Declare pointer to father. Successively, assign addresses of objects

Page 7: c++ Lab Exercises

of the two derived classes to this pointer and in each case, call iam() through the pointer to demonstrate polymorphism in action.

WEEK X

1. Write a program that uses a for structure to print a table of ASCII values for the characters in the ASCII character set from 33 to 126. The program should print the decimal value, octal value, hexadecimal value and character value for each character. Use the stream manipulators dec, oct and hex to print the integer values.

2. Write a program which counts and displays the number of characters in its own source code file.

3. Write a program that i. Starts with the output test statement:

cout<< “Testing:”<< 16/2 << “ = “<< 4*2 <<”.\n\n”; and thenii. Outputs its own C++ source file to a file called “withoutcomments.cpp” and to the

screen, but omitting any of the comments enclosed in “/* …… */” markers. The new program in the file “withoutcomments.cpp” should compile and run in exactly the same way as the program from which it was generated.

WEEK XI

1. Write a program to define a function template for summing an array of integers and an array of floating point numbers.

2. Write a simple function template for predicate function isEqualTo that compares its two arguments of the same type with the equality operator (==) and returns true if they are equal and false if they are not equal. Use this function template in a program that calls isEqualTo only with a variety of built-in types. Now write a separate version of the program that calls isEqualTo with a user-defined class type, but does not overload the equality operator. What happens when you attempt to run this program? Now overload the equality operator (with the operator function) operator==. Now what happens when you attempt to run this program?

WEEK XII

1. Suppose a program throws an exception and the appropriate exception handler begins executing. Now suppose the exception handler itself throws the same exception. Does this create an infinite recursion? Write a program to check your observation.

2. Use inheritance to create a base exception class and various derived exception class. Then show that a catch handler specifying the base class can catch derived class exceptions.

Page 8: c++ Lab Exercises

3. Write a program designed to generate and handle a memory exhaustion error. Your program should loop on a request to create dynamic storage through operator new.