You are on page 1of 22

Lab 1

- Introduction to C++ - Control Structures


NOTE Most of the commands and statements in C can also be used in C++ but not all. 1. printf is replaced with cout statement. It is pronounced as see out. This cout statement displays on the monitor whatever is transmitted to it. It is defined in library iostream.h ( Input & Output stream). Example:
// This is to explain about cout #include <iostream.h> int main( ) { cout << Assalamu Alaikkum; return 0; }

2. In C++, the new line character can also be used as we do in C (\n) e.g Replace the previous cout statement with the following statement in the above program
cout <<Assalamu Alaikkum \n Welcome to Visual C++ \n\nThank you;

3. endl (end line) can also be used instead of \n. The following program will illustrate the use of endl.
// This program is to explain the use of endl #include <iostream.h> int main( ) { cout << Assalamu Alaikkum << endl; cout << Welcome to Visual C++ << endl << Thank You; return 0; }

4. Comments can also be given to the program as we do in C programming using line comment (// ) and Block comment (/* */) . 5. There are many format specifiers in C++ which are used to format the desired output. setw(n)- set the field width to n places. setprecision(n) set the floating-point to n places setiosflags(flags) set the format flags( There are many format flags for use with setiosflags( ) e.g ios::showpoint, ios::fixed, etc.,) All the above format manipulators are defined in iomanip.h ( Input & Output manipulator)

AITA LAB MANUAL

The following program will explain the use of format manipulators


// This is to explain the use of Format manipulator #include <iostream.h> #include <iomanip.h> int main( ) { cout << Without Format Manipulator << endl; cout << 6 << endl << 18 << endl << 124 << endl << ---\n << (6+18+124) << endl << endl; cout << With format manipulator << endl; cout << setw(3) << 6 << endl << setw(3) << 18 << endl << setw(3) << 124 << endl << ---\n << (6+18+124) << endl; return 0; }

6. cin statement. It will do same function as scanf in C. It is used to enter data into a program while it is executing. It is pronounced as See in. The following program will illustrate the use of cin statements.
#include <iostream.h> int main( ) { float num1, num2, product; cout << Please type in a number:; cin >> num1; cout << Please type in another number:; cin >> num2; product = num1 * num2; cout << num1 << times << num2 << is << product << endl; return 0; }

AITA LAB MANUAL

Assignment Develop a C++ program that will determine if a department-store customer has exceeded the credit limit on a charge account. For each customer, the following information is available: 1- account number(an integer); 2- balance at the beginning of the month; 3- total of all items charged by the customer this month; 4- total of all credits applied to the customers account this month; 5- allowed credit limit. The program should input this information, calculate the new balance (= beginning balance + charges credits) and determine if the new balance exceeds the customers credit limit. For those customers whose credit limit is exceeded, the program should display the customers account number, credit limit, new balance and the message Credit limit exceeded.

Sample Output Enter account number (enter -1 to exit): 100 Enter beginning balance: 5394.78 Enter total charges: 1000.00 Enter total credits: 500.00 Enter credit limit: 5500.00 Account: 100 Credit Limit: 5500.00 Balance: 5894.78 Credit Limit Exceeded. Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter account number (enter -1 to exit): 200 beginning balance: 1000.00 total charges: 123.45 total credits: 321.00 credit limit: 1500.00 account number (enter -1 to exit): 300 beginning balance: 500.00 total charges: 274.73 total credits: 100.00 credit limit: 800.00

Enter account number (enter -1 to exit): -1

AITA LAB MANUAL

Lab 2
- Functions - Arrays - Pointers and Strings
NOTE Functions Although object-oriented programming has shifted attention from functions and toward objects, functions nonetheless remain a central component of any program. Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize them into subprograms. These subprograms are called functions. They can be compiled and tested separately and reused in different programs. This modularization is characteristics of successful object oriented software. A function is, in effect, a subprogram that can act on data and return a value. Every C++ program has at least one function, main( ).When your program starts, main() is called automatically. main( ) might call other functions, some of which might call still others. Each function has its own name, and when that name is encountered, the execution of the program branches to the body of that function. When the function returns, execution resumes on the next line of the calling function. Functions come in two varieties: user-defined and built-in. Built-in functions are part of your compiler package--they are supplied by the manufacturer for your use.
User Defined Functions: #include <iostream.h> double celsius(double); // Function prototype int main( ) { int j; double fren; for ( j = 1; j <= 5; j++) { cout << Enter a Fahrenheit temparature: << endl; cin >> fren; cout << The Celsius equivalent is << celsius(fren) << endl; cout << endl; } return 0; } double celsius(double f) { double cel; cel = 5.0/9.0 * (f-32); return cel; }

AITA LAB MANUAL

Arrays An array is a sequence of objects all of which have the same data type. The objects are called the elements of the array and are numbered consecutively 0,1,2,3 . These numbers are called index values or subscripts of the array. The term subscript is used because as a mathematical sequence, an array would be written with subscripts: a0, a1,a2 These numbers locate the elements position within the array, thereby giving direct access into the array. The concept of array in C and C++ is the same and so it is not discussed in depth. However, there are some basic things to be discussed to revise your concept of array. Lets start with the declaration of array. Syntax: data-type array-name[number of terms]; e.g int current[10]; If the name of the array is a, then a[0] is the name of the element that is in position 0, a[1] is the name of the element that is in position 1, etc. In general, the ith element is in position i-1. So if the array has n elements, their names are a[0], a[1], a[2], , a[n-1]. One dimensional array is not discussed here since it was covered in the previous course but the two dimensional array is covered in the following example. Two Dimensional Arrays Run the following program and try to understand the use of two-dimensional arrays.
#include <iostream.h> #include <iomanip.h> int main( ) { const int ROWS = 3; const int COLS = 4; int x, y; int val[ROWS][COLS] = {{8, 6, 9, 52},{3,15,27,6},{14,25,2,10}}; // Multiply each element by 10 and display it cout << "\n Display of multiplied elements"; for ( x = 0; x < ROWS; x++) { cout << endl; for(y = 0; y < COLS; y++) { val[x][y] *= 10; cout << setw(5) << val[x][y]; } } cout << endl; return 0; }

Pointers Pointers are variables that contain memory address as their values. A variable contains a specific value, whereas a pointer contains an address of a variable that contains a specific value. In other words a variable name directly references a value whereas a pointer indirectly references a value. Referencing a value through a pointer is called indirection. Pointers, like any other variables must be declared before they can be used. Lets see how pointers actually works with simple example, int count = 10, *count_ptr; declares an integer count with a value of 10, and also an integer pointer called count_ptr. Note that the prefix * defines the variable to be of type pointer. To set up an indirect reference between count and count_ptr, the prefix & is used ie., count_ptr = &count;

AITA LAB MANUAL

This assigns the memory address of count to count_ptr. Pointer operators: The &, address operator, is a unary operator that returns the address of its operand. The *, indirection or dereferencing, returns the value of the object to which its operand. ( i.e., a pointer ) points. Example:
/* Using the & and * operators */ #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 << endl; cout << " The value of aptr is "<< aptr << endl; cout << " The value of a is " << a << endl; cout << " The value of *aptr is " << *aptr << endl; cout << endl; cout << " Proving that * and & are complements of each other " << endl; cout << " &*aptr = " << *&aptr << endl; cout << " *&aptr = " << &*aptr << endl; return 0; }

Returning multiple values using reference Calling a function and passing arguments by value is a distinct advantage of C++. At no time, the called function have direct access to any variable defined in calling function, even if the variable is used as an argument in the function call. This is very clear from the above sample program. With this call by value, we can return only a single value from a single function. To return multiple values, we have to use the references of the variables. The following program will return(indirectly) the total and product of the three numbers from a single function.
#include <iostream.h> void calc(float, float, float, float&, float&); int main() { float x,y,z,sum,product; cout << " Enter the numbers " << endl; cin >> x >> y >> z; calc(x,y,z,sum,product); cout << " The sum of the numbers is " << sum << endl; cout << " The product of the numbers is " << product << endl; return 0; }

void calc(float x, float y, float z, float& sum, float&product) { sum = x+y+z; product = x*y*z; }

AITA LAB MANUAL

Assignment An integer is said to be prime if it is divisible only by two distinct factors, 1 and itself. For example, 2, 3, 5 and 7 are prime, but 4, 6, 8 and 9 are not. [Note: The number 1 is not a prime number.] Write a function that determines if a number is prime. Use this function in a program that determines and prints all the prime numbers between 1 and 100. Your output should look like this: Sample Output The prime numbers from 1 to 100 are: 2 3 5 7 11 13 17 19 31 37 41 43 47 53 59 61 73 79 83 89 97 23 67 29 71

AITA LAB MANUAL

Lab 3
- Classes and Data Abstraction - Classes: Part II
NOTE Classes extend the built-in capabilities of C++ to assist you in representing and solving complex, real-world problems. A class can consist of any combination of the variable types and also other class types. The variables in the class are referred to as the member variables or data members. A Car class might have member variables representing the seats, radio type, tires, and so forth. Member variables , also known as data members , are the variables in your class. Member variables are part of your class, just like the wheels and engine are part of your car. Member functions , also known as methods , are the functions in your class. Member functions are as much a part of your class as the member variables. They determine what the objects of your class can do. The functions in the class typically manipulate the member variables. They are referred to as member functions or methods of the class. Methods of the Car class might include Start() and Brake(). A Cat class might have data members that represent age and weight; its methods might include Sleep(), Meow(), and ChaseMice(). Class Declaration: To declare a class, use the classkeyword followed by an opening brace, and then lists the data members and methods of that class. End the declaration with a closing brace and a semicolon. E.g,
class Cat { private: int itsAge; int itsWeight; public: Meow(); };

After declaring the class, we have to define all the member functions and test our class with suitable driver (main) program. Compile and run the following example.
#include <iostream.h> #include <iomanip.h> class Date // Class Declaration { private: int month; int day; int year; public: Date(int = 7, int = 4, int = 2001); // Constructor void setdate(int,int,int); // Member function to copy a date

AITA LAB MANUAL

};

void showdate(void); //Member function to display a date

// Class Implementation Date::Date(int mm, int dd, int yyyy) { month = mm; day = dd; year = yyyy; } void Date::setdate(int mm, int dd, int yyyy) { month = mm; day = dd; year = yyyy; } void Date::showdate(void) { cout << Date is; cout << setw(2) << month << / <<setw(2) << day << / <<setw(2) << year % 100 << endl; }int main( ) { Date a,b,c(10,12,200 0); // Declaring 3 objects b.setdate(12,25,2002); a.showdate( ); b.showdate( ); c.showdate( ); return 0; }

Static Class Members Static class data members share the same storage space for all objects of the class as such; they act as global variables for the class and provide a mean of communication between objects. Static data members must be declared as such within the class declaration section and are defined outside of the declaration section. Of course, we can use global variables instead of static variables, but it is not very safe. Such data could be modified anywhere in the program, could conflict with an identical variable name within a function, and certainly violates OOPs principle of data hiding. In addition to static data members, static member function can also be created. Such functions apply to a class as a whole rather than for individual class objects and can only access static data members and other static member functions of the class. The following program will give the clear conception of using static members.
#include <iostream.h> class Employee { private: static float tax_rate; int id_num; public: Employee(int = 0); // Constructor void display( );

AITA LAB MANUAL

};

static void disp( ); // Static Function

// Static member definition float Employee::tax_rate = 0.0025; Employee::Employee(int num) { id_num = num; } void Employee::display() { cout << "Employee number " << id_num << "has a tax rate of " << tax_rate << endl; } void Employee::disp() { cout << " The static tax rate is " << tax_rate << endl; } int main() { Employee::disp(); // call the static functions Employee x(111), y(112); x.display(); y.display(); return 0; }

AITA LAB MANUAL

10

Assignment Create a class called Complex for performing arithmetic with complex numbers. Write a driver program to test your class. Complex numbers have the form realPart + imaginaryPart * i where i is __ -1 Use floating-point variables to represent the private data of the class. Provide a constructor function that enables an object of this class to be initialized when it is declared. The constructor should contain default values in case no initializers are provided. Provide public member functions for each of the following: a- Addition of two Complex numbers: The real parts are added together and the imaginary parts are added together. b- Subtraction of two Complex numbers: The real part of the right operand is subtracted from the real part of the left operand and the imaginary part of the right operand is subtracted from the imaginary part of the left operand. c- Printing Complex numbers in the form (a, b) where a is the real part and b is the imaginary part. Sample Output (1, 7) + (9, 2) = (10, 9) (10, 1) (11, 5) = (-1, -4)

AITA LAB MANUAL

11

Lab 4
- Operator Overloading - Friend Functions
NOTE Operator Overloading Operator overloading is the process by which you apply operators to your own abstract data types. It has some similarities to Polymorphism in the sense that both refer to the ability to use a single name to communicate multiple meaning. For now, think of operator overloading as a primitive type of polymorphism. It is easy to distinguish between overloading and polymorphism more precisely after completing this lab.
#include <iostream.h> class Employee { private: int idnum; double salary; public: Employee(int id, double sal); double addTwo( Employee &emp); double operator+( Employee &emp); }; Employee::Employee(int id, double sal) { idnum = id; salary = sal; } double Employee::addTwo( Employee &emp) { double total; total = salary + emp.salary; return total; } double Employee::operator+( Employee &emp) { double total; total = salary + emp.salary; return total; } void main() { Employee aClerk(222, 415.75), aDriver(333,612.44); double sum; sum = aClerk.addTwo(aDriver); cout << " Using addTwo( ) : " << sum << endl; sum = aClerk.operator+(aDriver);

AITA LAB MANUAL

12

cout << " Using operator+( ) : " << sum << endl; sum = aClerk + aDriver; cout << " Using +: " << sum << endl;

Friend functions Friend functions are granted the same privileges as member functions. The nonmember functions on the list are called friend function and the list is referred to as a friend list. Any functions attempting to access an objects private data members are first checked against the friend list: if the function is on the list, access is approved, otherwise access is denied. A friend function of a class is defined outside the class's scope. It has the right to access private members of the class. A function or an entire class may be declared to be a friend of another class. Friendship is neither symmetric nor transitive. It is possible to specify overloaded functions as friends of a class. Each overloaded function intended to be a friend must be explicitly declared in the class definition as a friend of the class. Run the following and try to understand the use of friend lists.
#include <iostream.h> #include <math.h> class Complex // Class Declaration { // Friends lists friend float addreal(Complex&, Complex&); friend float addimag(Complex&, Complex&);

private: float real; float imag; public: Complex(float=0,float=0); // Constructor void display(); }; Complex::Complex(float re, float im) { real = re; imag = im; } void Complex::display() { char sign = '+'; if(imag < 0) sign = '-'; cout << real <<sign << fabs(imag) << 'i' << endl; } // Friend Implementation float addreal(Complex &a, Complex &b) { float addre; addre = a.real + b.real; return addre; } float addimag(Complex &a, Complex &b) {

AITA LAB MANUAL

13

float addim; addim = a.imag + b.imag; return addim;

int main() { Complex a(3.4,6.7),b(1.3,-9.8); float sum_re, sum_im; cout << " \nThe first Complex number is "; a.display(); cout << " \nThe second Complex number is "; b.display(); sum_re = addreal(a,b); sum_im = addimag(a,b); Complex c(sum_re,sum_im); cout<< "\n\n The sum of the these two complex numbers is "; c.display(); return 0; }

AITA LAB MANUAL

14

Assignment Construct a class named Coord that contains two floating-point data members named xval and yval, which will be used to store the x and y of a point in rectangular coordinates. The function members should include appropriate constructor, display() function and a friend function named conv_pol(). The conv_pol() function should accept two floating-point numbers that represents a point in polar coordinates and convert them into rectangular coordinates. For conversion from polar to rectangular coordinates use the following formulas x = r cos y = r sin

AITA LAB MANUAL

15

Lab 5
- Object-Oriented Programming: Inheritance
NOTE For a language to be classified as object-oriented it must also provide inheritance and polymorphism. Inheritance is the capability to derive one class from another. A derived class is a completely new data type that incorporates all of the data member and member functions of the original class with any new data and functions members unique to itself. The class used as the basis for the derived type is referred to as the base or parent class and the derived data type is referred to as the derived or child class. A derived class has the same form as any other class in that it consists of both a declaration and an implementation. The only difference is in the first line of the declaration section. For a derived class this line is extended to include an access specification and a base class name has the form: class derived-class-name : class-access base-class-name To illustrate the concept of inheritance we will derive a Box class from a base class Rectangle. The following program listing is the implementation of the two classes.
#include <iostream.h> #include <math.h> const double PI = 2.0 * asin(1.0); class Circle { protected: double radius; public: Circle(double = 1.0); double area( ); }; Circle::Circle(double r) { radius = r; } double Circle::area( ) { return (PI*radius*radius); } class Cylinder : public Circle { protected: double length; public: Cylinder (double r = 1.0, double l = 1.0); double area ( ); };

AITA LAB MANUAL

16

Cylinder::Cylinder(double r, double l ) { radius = r; length = l; } double Cylinder::area( ) { return (length*Circle::area()); } int main ( ) { Circle circle_1, circle_2 (2); Cylinder cylinder_1(3,4); cout <<"\n The area of circle_1 is " << circle_1.area(); cout <<"\n The area of circle_2 is " << circle_2.area(); cout <<"\n The volume of cylinder_1 is" << cylinder_1.area(); circle_1 = cylinder_1; cout <<"\nThe area of circle_1 is now " << circle_1.area() << endl << endl; return 0; }

AITA LAB MANUAL

17

Assignment Develop a class Racecar that inherits publicly from class Car, which represents a car by its maximum speed, the number of engine valves, its color and its name. A Racecar is distinguished by its gearbox (the number of gears it has), and its sponsor. Sample Output Chevy: Car: Chevrolette Color: Black Engine: 4-valve Max Speed: 95mph F1: Car: Ferrari Color: Red Engine: 40-valve Max Speed: 220mph Gears: 7 Sponsor: Bug2Bug

AITA LAB MANUAL

18

Lab 6
- Object Oriented Programming: Polymorphism
NOTE Polymorphism One of the most powerful features of C++ is that it allows objects of different types to respond differently to the same function call. When you can apply the same function name to different objects, your program can be developed more quickly and are easier to read. This is called Polymorphism and it is achieved by means of virtual functions. Creating a virtual function is extremely easy- all that is required is that the keyword virtual be placed before the functions return type in the declaration section. The following program will illustrate the concept of virtual functions.
#include <iostream.h> #include <math.h> class One { protected: float a; public: One(float = 2.0); virtual float f1(float); float f2(float); }; One::One(float val) { a = val; } float One::f1(float val) { return (val/2); } float One::f2(float val) { return ( pow(f1(val),2) ); } class Two : public One { public: virtual float f1(float); }; float Two::f1(float val) {

AITA LAB MANUAL

19

return (val/3);

int main() { One obj1; Two obj2; cout << " The computed value using a base class object call is " << obj1.f2(12) << endl; cout << "The computed value using a derived class object call is " << obj2.f2(12) << endl; cout << endl; return 0; }

AITA LAB MANUAL

20

Assignment Apply the concept of polymorphism to a Vehicle hierarchy. Develop an abstract base class Vehicle that includes the vehicles name, color, number of doors, number of cylinders, transmission type and fuel level. Add a member function named horn that displays the sound made by the Vehicles horn. The print member function and the horn member function should both be virtual functions; horn should be a pure virtual function. Class Taxi and class Truck should both be derived from Vehicle. Write a driver program to test the class hierarchy. Instantiate one object of type Taxi and one object of type Truck. Insert those objects into a container-a vector of base-class pointers. For each object in the vector, call virtual functions horn and print. Sample Output The vehicle cannot get out of their parking spaces because of traffic, so they respond: Beep beep Number of doors: 4 Number of cylinders: 6 Transmission type: 5 Color: yellow Fuel level: 3.3 The taxi currently has no passengers. Class name: Taxi HOOOONK! Number of doors: 2 Number of cylinders: 16 Transmission type: 8 Color: black Fuel level: 7.54 The truck is currently carrying cargo. Class name: Truck

AITA LAB MANUAL

21

AITA LAB MANUAL

22

You might also like