29
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”; AITA LAB MANUAL 1

c++ Assignment

Embed Size (px)

Citation preview

Page 1: c++ Assignment

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.gReplace 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 placessetiosflags(flags) – set the format flags( There are many format flags for use withsetiosflags( ) e.g ios::showpoint, ios::fixed, etc.,)

AITA LAB MANUAL1

Page 2: c++ Assignment

All the above format manipulators are defined in iomanip.h ( Input & Outputmanipulator)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 MANUAL2

Page 3: c++ Assignment

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 customer’s 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 customer’s credit limit. For those customers whose credit limit is exceeded, the program should display the customer’s account number, credit limit, new balance and the message “Credit limit exceeded.”

Sample Output

Enter account number (enter -1 to exit): 100Enter beginning balance: 5394.78Enter total charges: 1000.00Enter total credits: 500.00Enter credit limit: 5500.00Account: 100Credit Limit: 5500.00Balance: 5894.78Credit Limit Exceeded.

Enter account number (enter -1 to exit): 200Enter beginning balance: 1000.00Enter total charges: 123.45Enter total credits: 321.00Enter credit limit: 1500.00

Enter account number (enter -1 to exit): 300Enter beginning balance: 500.00Enter total charges: 274.73Enter total credits: 100.00Enter credit limit: 800.00

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

AITA LAB MANUAL3

Page 4: c++ Assignment

Lab 2

- Functions- Arrays- Pointers and Strings

NOTE

FunctionsAlthough object-oriented programming has shifted attention from functions and

toward objects, functions nonetheless remain a central component of any program. Mostuseful programs are much larger than the programs that we have considered so far. Tomake large programs manageable, programmers modularize them into subprograms.These subprograms are called functions. They can be compiled and tested separately andreused 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 calledautomatically. 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 theprogram branches to the body of that function. When the function returns, executionresumes on the next line of the calling function.

Functions come in two varieties: user-defined and built-in. Built-in functions arepart of your compiler package--they are supplied by the manufacturer for your use.

User Defined Functions:

#include <iostream.h>double celsius(double); // Function prototypeint 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){

AITA LAB MANUAL4

Page 5: c++ Assignment

double cel;cel = 5.0/9.0 * (f-32);return cel;

}

ArraysAn 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” isused because as a mathematical sequence, an array would be written with subscripts: a0,a1,a2… These numbers locate the element’s position within the array, thereby givingdirect access into the array. The concept of array in C and C++ is the same and so it is notdiscussed in depth. However, there are some basic things to be discussed to revise yourconcept of array. Let’s 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 inposition 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 coursebut the two dimensional array is covered in the following example.

Two Dimensional ArraysRun 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 itcout << "\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;

}

PointersPointers 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 containsa specific value. In other words a variable name directly references a value whereas apointer indirectly references a value. Referencing a value through a pointer is calledindirection. Pointers, like any other variables must be declared before they can be used.Lets see how pointers actually works with simple example,

AITA LAB MANUAL5

Page 6: c++ Assignment

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 indirectreference between count and count_ptr, the prefix & is used ie.,count_ptr = &count;This assigns the memory address of count to count_ptr.Pointer operators: The &, address operator, is a unary operator that returns the address ofits operand. The *, indirection or dereferencing, returns the value of the object to whichits 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 integera = 7;aptr = &a; // aptr set to address of acout << " 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 referenceCalling 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 callingfunction, even if the variable is used as an argument in the function call. This is veryclear from the above sample program.With this call by value, we can return only a single value from a single function. Toreturn multiple values, we have to use the references of the variables.The following program will return(indirectly) the total and product of the three numbersfrom 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;

AITA LAB MANUAL6

Page 7: c++ Assignment

product = x*y*z;}

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 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

AITA LAB MANUAL7

Page 8: c++ Assignment

Lab 3

- Classes and Data Abstraction- Classes: Part II

NOTE

Classes extend the built-in capabilities of C++ to assist you in representing and solvingcomplex, real-world problems. A class can consist of any combination of the variabletypes and also other class types.

The variables in the class are referred to as the member variables or data members. ACar class might have member variables representing the seats, radio type, tires, and soforth. 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 yourcar.

Member functions , also known as methods , are the functions in your class. Memberfunctions are as much a part of your class as the member variables. They determine whatthe objects of your class can do. The functions in the class typically manipulate themember 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 mighthave data members that represent age and weight; its methods might include Sleep(),Meow(), and ChaseMice().

Class Declaration:To declare a class, use the class keyword followed by an opening brace, and then liststhe data members and methods of that class. End the declaration with a closing brace anda 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 classwith suitable driver (main) program. Compile and run the following example.#include <iostream.h>#include <iomanip.h>class Date // Class Declaration

AITA LAB MANUAL8

Page 9: c++ Assignment

{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 void showdate(void); //Member function to display a date};

// Class ImplementationDate::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 MembersStatic class data members share the same storage space for all objects of the classas such; they act as global variables for the class and provide a mean of communicationbetween objects. Static data members must be declared as such within the classdeclaration section and are defined outside of the declaration section. Of course, we canuse global variables instead of static variables, but it is not very safe. Such data could bemodified anywhere in the program, could conflict with an identical variable name withina function, and certainly violates OOP’s principle of data hiding. In addition to static datamembers, static member function can also be created. Such functions apply to a class as awhole rather than for individual class objects and can only access static data membersand other static member functions of the class. The following program will give the clearconception of using static members.#include <iostream.h>class Employee

AITA LAB MANUAL9

Page 10: c++ Assignment

{ private: static float tax_rate; int id_num;public: Employee(int = 0); // Constructor void display( ); static void disp( ); // Static Function};

// Static member definitionfloat 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 MANUAL10

Page 11: c++ Assignment

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 * iwhere 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 MANUAL11

Page 12: c++ Assignment

Lab 4

- Operator Overloading- Friend Functions

NOTE

Operator OverloadingOperator overloading is the process by which you apply operators to your own abstractdata types. It has some similarities to Polymorphism in the sense that both refer to theability to use a single name to communicate multiple meaning. For now, think of operatoroverloading as a primitive type of polymorphism. It is easy to distinguish betweenoverloading 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;}

AITA LAB MANUAL12

Page 13: c++ Assignment

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); cout << " Using operator+( ) : " << sum << endl; sum = aClerk + aDriver; cout << " Using +: " << sum << endl;}

Friend functionsFriend functions are granted the same privileges as member functions. The nonmemberfunctions on the list are called friend function and the list is referred to as afriend list. Any functions attempting to access an object’s private data members are firstchecked against the friend list: if the function is on the list, access is approved, otherwiseaccess is denied.A friend function of a class is defined outside the class's scope. It has the right to accessprivate members of the class. A function or an entire class may be declared to be a friendof another class. Friendship is neither symmetric nor transitive. It is possible to specifyoverloaded functions as friends of a class. Each overloaded function intended to be afriend 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 listsfriend 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 Implementationfloat addreal(Complex &a, Complex &b){ float addre;

AITA LAB MANUAL13

Page 14: c++ Assignment

addre = a.real + b.real; return addre;}

float addimag(Complex &a, Complex &b){ 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 MANUAL14

Page 15: c++ Assignment

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 formulasx = r cos y = r sin

AITA LAB MANUAL15

Page 16: c++ Assignment

Lab 5

- Object-Oriented Programming: Inheritance

NOTE

For a language to be classified as object-oriented it must also provide inheritance andpolymorphism. Inheritance is the capability to derive one class from another. A derivedclass is a completely new data type that incorporates all of the data member and memberfunctions 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 classand 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 adeclaration and an implementation. The only difference is in the first line of thedeclaration section. For a derived class this line is extended to include an accessspecification and a base class name has the form:class derived-class-name : class-access base-class-nameTo illustrate the concept of inheritance we will derive a Box class from a base classRectangle. 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); }

AITA LAB MANUAL16

Page 17: c++ Assignment

class Cylinder : public Circle{ protected: double length;public: Cylinder (double r = 1.0, double l = 1.0); double area ( );};

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 MANUAL17

Page 18: c++ Assignment

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: ChevroletteColor: BlackEngine: 4-valveMax Speed: 95mph

F1:Car: FerrariColor: RedEngine: 40-valveMax Speed: 220mphGears: 7Sponsor: Bug2Bug

AITA LAB MANUAL18

Page 19: c++ Assignment

Lab 6

- Object Oriented Programming: Polymorphism

NOTE

PolymorphismOne of the most powerful features of C++ is that it allows objects of different types torespond differently to the same function call. When you can apply the same functionname to different objects, your program can be developed more quickly and are easier toread. 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 keywordvirtual be placed before the function’s return type in the declaration section. Thefollowing 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) ); }

AITA LAB MANUAL19

Page 20: c++ Assignment

class Two : public One{ public: virtual float f1(float); };

float Two::f1(float val){ 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 MANUAL20

Page 21: c++ Assignment

Assignment

Apply the concept of polymorphism to a Vehicle hierarchy. Develop an abstract base class Vehicle that includes the vehicle’s 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 Vehicle’s 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 beepNumber of doors: 4Number of cylinders: 6Transmission type: 5Color: yellowFuel level: 3.3The taxi currently has no passengers.Class name: Taxi

HOOOONK!Number of doors: 2Number of cylinders: 16Transmission type: 8Color: blackFuel level: 7.54The truck is currently carrying cargo.Class name: Truck

AITA LAB MANUAL21

Page 22: c++ Assignment

AITA LAB MANUAL22