a19
DESCRIPTION
iit ggeTRANSCRIPT
C++ Class Assignments
2
Lecture No- 1 Assignment No- 1
Objectives:
Write a simple program in C++ to display “Hello World”. Command to be Used 1. Cout<< Output:
#include<iostream.h> #include<conio.h> void main() {
cout<<“Hello World.”; getch();
}
C++ Class Assignments
3
Lecture No- 2 Assignment No- 1
Objective
Write a program to accept the radius of circle and display area of the circle as output Command to be Used 1. Cin>> 2. Cout<< Output:
#include<iostream.h> #include<conio.h> #define PI 3.14 //define a constant //program to calculate area of circle void main() { float radius; clrscr(); cout<<"Enter radius of circle"<<endl; cin>>radius; cout<<"Area of circle is "<< 2 * PI * radius; //calulate the area of //circle getch(); }
C++ Class Assignments
4
Lecture No- 2 Assignment No- 2
Objective
Write a program to process an order of pants, shirts, dresses, tie and display the invoice.
Command to be Used
1. Cin.getline() 2. Variables 3. Operators
Output:
C++ Class Assignments
5
#include <iostream.h> #include <conio.h> int main() { char customerName[60], customerPhone[20]; unsigned short shirts; unsigned short pants; unsigned short dresses; unsigned short ties; unsigned short totalItems; double priceShirts = 1.25; double pricePants = 2.75; double priceDresses = 3.25; double priceTies = 1.65; double taxRate = 5.75; // 5.75% double totalCostShirts, totalCostPants, totalCostDresses, totalCostTies; double totalCostCleaning; double amountTended, difference; double taxAmount, netPrice; int orderDay; int orderMonth; int orderYear; clrscr(); cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter Customer Name: "; cin >> ws; cin.getline(customerName, 60); cout << "Enter Customer Phone: "; cin.getline(customerPhone, 20); cout << "Enter the date this order was placed(dd mm yyyy)\n"; cin >> orderDay >> orderMonth >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties; totalItems = shirts + pants + dresses + ties; totalCostShirts = shirts * priceShirts; totalCostPants = pants * pricePants; totalCostDresses = dresses * priceDresses; totalCostTies = ties * priceTies; totalCostCleaning = totalCostShirts + totalCostPants +
C++ Class Assignments
6
totalCostDresses + totalCostTies; taxAmount = totalCostCleaning * taxRate / 100; netPrice = totalCostCleaning + taxAmount; cout << "The total order is: " << netPrice << "\n"; cout << "Amount Tended: "; cin >> amountTended; difference = amountTended - netPrice; cout << "\n===================================="; cout << "\n-=- Georgetown Cleaning Services -=-"; cout << "\n===================================="; cout << "\nCustomer Order"; cout << "\nCustomer Name: " << customerName; cout << "\nCustomer Phone: " << customerPhone; cout << "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Unit Price Qty Sub-Total"; cout << "\n------------------------------------" << "\nShirts: " << priceShirts << " " << shirts << " " << totalCostShirts << "\nPants: " << pricePants << " " << pants << " " << totalCostPants << "\nDresses: " << priceDresses << " " << dresses << " " << totalCostDresses << "\nTies: " << priceTies << " " << ties << " " << totalCostTies; cout << "\n------------------------------------" << "\nTotal Number of Items: " << totalItems << "\nTotal Cleaning of Items: " << totalCostCleaning << "\nTax Rate: " << taxRate << "%" << "\nTax Amount: " << taxAmount << "\nNet Price: " << netPrice << "\nAmount Tended: " << amountTended << "\nDifference: " << difference << "\n"; getch(); return 0; }
C++ Class Assignments
7
Lecture No- 3 Assignment No- 1
Objective:
Write a program take input for transaction type as Deposit, Withdraw, Transfer and amount and display the message according to the Transaction type using Nested If Else. Command to be Used
1. If…else if
Output:
C++ Class Assignments
8
/* PROGRAM TO USE NESTED IF STATEMENT IN C++*/ #include <iostream.h> #include<conio.h> void main() { float amount; char transaction_code; clrscr(); cout<<"D - Cash Deposit, W - Cash Withdrawal, T - Cash Transfer\n"; cout<<"\nEnter the transaction code(D, W, T); "; cin>>transaction_code; if (transaction_code == 'D') { cout<<"\nDeposit transaction"; cout<<"\nEnter amount: "; cin>>amount; cout<<"\nPROCESSING....Please Wait"; cout<<"\nAmount deposited: "<<amount; cout<<"\n---THANK YOU!---"; } else if (transaction_code == 'W') { cout<<"\nWithdrawal transaction"; cout<<"\nEnter amount: "; cin>>amount; cout<<"\nPROCESSING....Please Wait"; cout<<"\nAmount withdrawn: "<<amount;
C++ Class Assignments
9
cout<<"\n---THANK YOU!---"; } else if (transaction_code == 'T') { cout<<"\nTransfer transaction"; cout<<"\nEnter amount: "; cin>>amount; cout<<"\nPROCESSING....Please Wait"; cout<<"\nAmount transferred: "<<amount; cout<<"\n---THANK YOU!---"; } else { cout<<"\nInvalid transaction!!"; cout<<"D = Deposit, W = Withdrawal, T = Transfer"; cout<<"\nPlease enters the correct transaction code: "; } cout<<"\n"; getche(); }
C++ Class Assignments
10
Lecture No- 3 Assignment No- 2
Objective:
Write a program for creating the multiplication table for the entered number Command to be Used
1. For…Loop Output:
#include<iostream.h> #include<conio.h> //loops //for loop void main() { int a,n; clrscr(); cout<<"enter a number for multiplication table"<<endl; cin>>n; for(a=1;a<=10;a++) { cout<<n<<" x "<<a<<" = "<<n*a<<endl; } getch(); }
C++ Class Assignments
11
Lecture No- 3 Assignment No- 3
Objective:
Write a program using nested…for loop. Command to be Used
1. Nested For…Loop Output:
#include<iostream.h> #include<conio.h> //loops //for loop void main() { int i,j; cout<<"Number Triangle \n"; for(i=1;i<=7;i++) { for(j=1;j<=i;j++) { cout<<j; } cout<<"\n"; } }
C++ Class Assignments
12
Lecture No. 3 Assignment No.4
Objective Write a program to accept a month in number and display name of month Commands to be used
1. switch case Output
#include<conio.h> #include<stdio.h> #include<iostream.h> void main<<) { int month; clrscr<<); cout<<“Enter any month in number\n”; Cin >>month; Switch<<month) { case 1: cout<<“January”; break; case 2: cout<<“February”; break; case 3: cout<<“March”; break; case 4: cout<<“April”; break; case 5: cout<<“May”; break; case 6: cout<<“June”; break; case 7: cout<<“July”; break; case 8: cout<<“August”; break; case 9: cout<<“September”; break; case 10: cout<<“October”; break; case 11: cout<<“November”; break; case 12: cout<<“December”; break; default: cout<<“Invalid month.”;break; } getch(); }
C++ Class Assignments
13
Lecture No- 4 Assignment No-1
Objective:
Write a program for finding the maximum member of an array Command to be Used
1. For 2. If 3. Single Dimensional Array
Output:
// Example of finding the maximum member of an array #include <iostream.h> #include <conio.h> int main() { // The members of the array int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89}; int maximum = numbers[0]; int a = 8; // Compare the members for (int i = 1; i < a; ++i) { if (numbers[i] > maximum) maximum = numbers[i]; } // Announce the result cout << "The highest member value of the array is " << maximum << "." << endl; getch(); return 0; }
C++ Class Assignments
14
Lecture No- 4 Assignment No- 2
Objective:
Write a program for printing data Command to be Used
1. For 2. Single Dimensional Array 3. Double Dimensional Array
Output:
// Example of finding the maximum member of an array #include <iostream.h> #include <conio.h> int main() { // The members of the array int bk_id[4]={1,2,3,4}; char title[4][20]={"Jungle book","Twinkle","Little Stars","Dog and The Bone"}; cout<<"----------------------------------"; cout<<"\nBook Id"<<"\t\t"<<"Title"; cout<<"\n----------------------------------\n"; for(int i=0;i<4;i++) { cout<<bk_id[i]<<"\t\t"<<title[i]<<endl; } cout<<"\n----------------------------------"; getch(); return 0; }
C++ Class Assignments
15
Lecture No- 5 Assignment No- 1
Objective
Create program where Date of Birth stored in variable of user defined data type using structure Output:
#include<iostream.h> #include<conio.h> #include<string.h> //structures struct Date { int Dt; char month[5]; int year; char day[5]; }; void main() { struct Date Nittin_DOB; Nittin_DOB.Dt=25; strcpy(Nittin_DOB.month,"Jan"); Nittin_DOB.year=1978; strcpy(Nittin_DOB.day,"Wed"); clrscr(); cout<<"Nittin's Date of birth is "<<Nittin_DOB.Dt<<"/"<<Nittin_DOB.month<<"/"<<Nittin_DOB.year<<", "<<Nittin_DOB.day; getch(); }
C++ Class Assignments
16
Lecture No- 5 Assignment No- 2
Objective:
Write a program with enum data type. Command to be Used
1. enum Output:
#include<iostream.h> #include<conio.h> enum e_acompany { Audi=4, BMW=5, Cadillac=11, Ford=44, Jaguar=45, Lexus, Maybach=55, RollsRoyce=65, Saab=111 }; void main() { clrscr(); e_acompany my_car; my_car = Ford; if (my_car == Ford) cout << "Hello, Ford-car owner!" << endl; else cout<< "Oh! No!"; getch(); }
C++ Class Assignments
17
Lecture No- 6 Assignment No- 1
Objective:
Write a program to display the String in Upper Case, Lower Case, in reveres order, copy one string into another also calculate its length and compare two String. Command to be Used 1. String functions Output:
#include<stdio.h> #include<conio.h> #include<string.h> void main() { char s1[20],s2[20]; int l; clrscr(); printf("enter a string\n"); scanf("%s",&s1); l=strlen(s1);//length of string printf("\nLength of the string is %d",l); strupr(s1);//capital letters printf("\ns1 in Upper Case is %s",s1); strlwr(s1);//lower case printf("\ns1 in lower case is %s",s1);
C++ Class Assignments
18
strcpy(s2,s1);//copy s1 into s2 printf("\nCopy Strinf s1 into s2 is %s",s2); strcat(s1," patel");// or strcpy(s1,s2) --> add s2 to s1 printf("\nConcated String s1 with Patel is %s",s1); strrev(s1);//reverse the string printf("\nreversed order of s1 is %s",s1); getch(); }
C++ Class Assignments
19
Lecture No- 6 Assignment No- 2
Objective: Write a program to print system Date and Time.
Command to be Used Time functions
Output:
#include <dos.h> #include <stdio.h> #include<conio.h> #include<iostream.h> int main(void) { struct date d; clrscr(); getdate(&d); cout<<"The current year is:\t"<<(int)d.da_year; cout<<"\nThe current day is:\t"<<(int)d.da_day; cout<<"\nThe current month is:\t"<<(int)d.da_mon; getch(); return 0; }
C++ Class Assignments
20
Lecture No- 6 Assignment No- 3
Objective: This example demonstrates how to use some mathematics function like [acos(), asin(), atan(), atan2(), cos(), sin(), tan(), log(), log10(), pow(), sqrt(), ceil(), floor(), fmod(), abs(), labs()].
Command to be Used 1. acos() 2. asin() 3. atan() 4. atan2() 5. cos() 6. sin() 7. tan() 8. log() 9. log10() 10. pow() 11. sqrt() 12. ceil() 13. floor() 14. fmod() 15. abs() 16. labs()
Output:
C++ Class Assignments
21
#include<stdio.h> #include<conio.h> #include<math.h> void main() { int non_abs=-1230; long result; long x = -12345678L; double d1 = 5.0, d2 = 2.0; double number = 123.54; double down, up; double at1, at2; clrscr(); printf(" Absolute value of %d = %d",non_abs, abs(non_abs)); result= labs(x); printf("\n Number: %ld Absolute value of long number: %ld\n", x, result); printf("\n The remainder of (%lf / %lf) is %lf", d1, d2, fmod(d1,d2)); down = floor(number); up = ceil(number); printf("\n Number rounded down: %5.2lf", down); printf("\n Number rounded up: %5.2lf", up); printf("\n Square root of 16 = %lf", sqrt(9)); printf("\n Power of 9 = %lf", pow(9,2)); printf("\n The natural log of 800.6872 is: %lf", log(800.6872)); printf("\n The common log of 800.6872 is: %lf\n", log10(800.6872)); printf("\n The sin() of 0.5 is %lf", sin(0.5)); printf("\n The cosine of 0.5 is %lf", cos(0.5)); printf("\n The tan of 0.5 is %lf\n", tan(0.5)); printf("\n The arc sin of 0.5 is %lf", asin(0.5)); printf("\n The arc cosine of 0.5 is %lf", acos(0.5)); printf("\n The arc tangent of 0.5 is %lf", atan(0.5)); at1 = 90.0; at2 = 45.0; printf("\n The arc tangent ratio of %lf is %lf", (at2 / at1), atan2(at2, at1)); getch(); }
C++ Class Assignments
22
Lecture No- 7 Assignment No- 1
Objective
Create a function taking an integer parameter and return the value by incrementing it by 10 demonstrating the function call by value
Command to be Used
1. Functions Output:
#include <iostream> using namespace std; int incr10(int num); // Function prototype int main(void) { int num = 3; cout << endl << "incr10(num) = " << incr10(num) << endl << "num = " << num; cout << endl; return 0; } // Function to increment a variable by 10 int incr10(int num) // Using the same name might help... { num += 10; // Increment the caller argument - hopefully return num; // Return the incremented value }
C++ Class Assignments
23
Lecture No- 7 Assignment No- 2
Objective
Create a function taking an integer parameter as pointer and modify caller argument value by +10 demonstrating the function call by value
Command to be Used
1. Functions 2. Pointers
Output:
#include <iostream.h> #include <conio.h> int incr10(int* num); // Function prototype int main(void) { int num = 3; int* pnum = # // Pointer to num clrscr(); cout << endl << "Address passed = " << pnum; cout << endl << "incr10(pnum) = " << incr10(pnum); cout << endl << "num = " << num; cout << endl; getch(); return 0; } // Function to increment a variable by 10 int incr10(int* num) // Function with pointer argument {
C++ Class Assignments
24
cout << endl << "Address received = " << num; *num += 10; // Increment the caller argument - confidently return *num; // Return the incremented value }
C++ Class Assignments
25
Lecture No- 8 Assignment No- 1
Objective: Create a simple class for representing student and add attributes like name, rollno, address, marks and create a method to calculate the grade and display the details of student Command to be Used
1. Class 2. Object 3. Access specifier
Output:
#include<conio.h> #include<iostream.h> #include<string.h> class Student { private: int Rollno; char name[10]; char Grade; public: char div; int std;
C++ Class Assignments
26
Student() { Rollno=1; strcpy(name,"Ajay"); Grade='B'; div='C'; std=11; } Student(int r,char n[10]) { Rollno=r; strcpy(name,n); Grade='B'; div='C'; std=11; } Student(int r,char n[10],char g,char d,int s) { Rollno=r; strcpy(name,n); Grade=g; div=d; std=s; } void display() { cout<<"\nRoll Number:"<<Rollno<<endl; cout<<"name:"<<name<<endl; cout<<"Grade:"<<Grade<<endl; cout<<"Division:"<<div<<endl; cout<<"Standard:"<<std<<endl; } }; void main() { Student std1(1,"prachi",'A','A',14),std2(2,"raju"),std3; clrscr(); std1.display(); std2.display(); std3.display(); getch(); }
C++ Class Assignments
27
Lecture No- 8 Assignment No- 2
Objective: Write a Program for defining member functions outside the class using scope resolution operator
Command Used/Concept:
1. Constructor Overloading 2. Private ,Public 3. Scope Resolution Operator
Output:
#include<conio.h> #include<iostream.h> #include<string.h> class Student { private: int Rollno; char name[10]; char Grade; public: char div; int std; Student() {
C++ Class Assignments
28
Rollno=1; strcpy(name,"Ajay"); Grade='B'; div='C'; std=11; } Student(int r,char n[10]) { Rollno=r; strcpy(name,n); Grade='B'; div='C'; std=11; } Student(int r,char n[10],char g,char d,int s) { Rollno=r; strcpy(name,n); Grade=g; div=d; std=s; } void display(); }; void Student::display() { cout<<"\nRoll Number:"<<Rollno<<endl; cout<<"name:"<<name<<endl; cout<<"Grade:"<<Grade<<endl; cout<<"Division:"<<div<<endl; cout<<"Standard:"<<std<<endl; } void main() { Student std1(1,"prachi",'A','A',14),std2(2,"raju"),std3; clrscr(); std1.display(); std2.display(); std3.display(); getch(); }
C++ Class Assignments
29
Lecture No- 9 Assignment No- 1
Objective:
Create a class where each object is a message of some description, for example, a text string. The class to be as memory efficient as possible, so, rather than defining a data member as a char array big enough to hold the maximum length string that might require, allocate memory on the free store for a message when an object is created
Command to be Used
1. Pointers 2. Reference operators
Output:
// Class with an explicit destructor #include <iostream.h> #include <conio.h> class Box // Class definition at global scope { public: // Destructor definition ~Box() { cout << "Destructor called." << endl; } // Constructor definition Box(double lv=1.0, double bv=1.0, double hv=1.0) { cout << endl << "Constructor called."; length = lv; // Set values of breadth = bv; // data members height = hv; } // Function to calculate the volume of a box double Volume() {
C++ Class Assignments
30
return length * breadth * height; } // Function to compare two boxes which // returns true if the first is greater // than the second, and false otherwise int compare(Box* pBox) { return this->Volume() > pBox->Volume(); } private: double length; // Length of a box in inches double breadth; // Breadth of a box in inches double height; // Height of a box in inches }; int main() { Box Boxes[5]; // Array of Box objects declared Box Cigar(8.0, 5.0, 1.0); // Declare Cigar box Box Match(2.2, 1.1, 0.5); // Declare Match box // Initialize pointer to Cigar object address Box* pB1 = &Cigar; Box* pB2 = 0; // Pointer to Box initialized to null clrscr(); cout << endl << "Volume of Cigar is " << pB1->Volume(); // Volume of obj. pointed to pB2 = Boxes; // Set to address of array Boxes[2] = Match; // Set 3rd element to Match cout << endl // Now access thru pointer << "Volume of Boxes[2] is " << (pB2 + 2)->Volume(); cout << endl; getch(); return 0; }
C++ Class Assignments
31
Lecture No- 9 Assignment No- 2
Objective: Write a program to perform the addition of two numbers using friend function Command Used:
1. Friend function Output:
#include<iostream.h> #include<conio.h> class exforsys { private: int a,b; public: void test() { a=100; b=200; } friend int compute(exforsys e1); }; int compute(exforsys e1) { //Friend Function Definition which has access to private data return int(e1.a+e1.b)-5; } void main() { clrscr(); exforsys e; e.test(); cout<<"The result is:"<<compute(e); getch(); //Calling of Friend Function with object as argument. }
C++ Class Assignments
32
Lecture No- 9 Assignment No- 3
Objective: Write a program to add two time values using friend function and scope resolution operator Command Used:
1. Scope resolution operator Output:
#include<iostream.h> #include<conio.h> class time { int min,sec; public: void gettime(int m,int s); void disptime(); void addtime(time,time); }; void time::gettime(int m,int s) { min=m; sec=s; } void time::disptime() { cout<<"\n\nMinutes :"<<min<<"\nSeconds :"<<sec; } void time::addtime(time t1,time t2) { min=t1.min+t2.min;
C++ Class Assignments
33
sec=t1.sec+t2.sec; while(sec>60) { min=min+1; sec=sec-60; } } void main() { clrscr(); time t3,t4,t5; t3.gettime(23,45); t4.gettime(12,45); t3.disptime(); t4.disptime(); t5.addtime(t3,t4); t5.disptime(); getch(); }
C++ Class Assignments
34
Lecture No- 10 Assignment No- 1
Objective Create a student class having attributes rollno, std, division, result and a constructor to initial Std and Division. Create two objects of this class and copy the std & division from first object into second using copy constructor. Command to be Used
1. Copy Constructor
Output:
#include<iostream.h> #include<conio.h> #include<string.h> //example of copy constructor class student { private: char division; int standard; public: char name[10]; int rollno; char result[10]; //constructor student(int std,char div) { standard=std; division=div; } void setvalues(int roll,char n[10],char r[10])
C++ Class Assignments
35
{ rollno=roll; strcpy(name,n); strcpy(result,r); } void showresult() { cout<<"\nstanndard:"<<standard; cout<<"\ndivision:"<<division; cout<<"\nrollno:"<<rollno; cout<<"\nName:"<<name; cout<<"\nResult:"<<result; } }; void main() { student std1(12,'D'); std1.setvalues(1,"krishan","pass"); clrscr(); std1.showresult(); student std2(std1); std2.setvalues(2,"raja","pass"); std2.showresult(); getch(); }
C++ Class Assignments
36
Lecture No- 10 Assignment No- 2
Objective: Create a rectangle class having constructor to initialize square and rectangle using constructor overloading Command to be Used
1. Constructor Overloading Output:
#include<iostream.h> #include<conio.h> #include<math.h> class rectangle { public: float l,b; //constructor for square rectangle(int x) { l=x; b=x; } //constructor for normal rectangle
C++ Class Assignments
37
rectangle(int x,int y) { l=x; b=y; } void length() { cout<<endl<<"l="<<l; } void breadth() { cout<<endl<<"b="<<b; } float area() { return(l*b); } float perimeter() { return(2*(l+b)); } float diagonal() { return sqrt((l*l)+(b*b)); } }; void main() { rectangle rect(5,4); rectangle square(5); clrscr(); cout<<"\n\n========RENTANGLE========"<<endl; rect.length(); rect.breadth(); cout<<endl<<"diagonal="<<rect.diagonal()<<endl; cout<<"Area of rectangle="<<rect.area()<<endl; cout<<"perimeter of rectangle="<<rect.perimeter(); cout<<"\n\n========SQUARE========"<<endl; square.length(); square.breadth(); cout<<endl<<"diagonal square="<<square.diagonal()<<endl;
C++ Class Assignments
38
cout<<"Area of square="<<square.area()<<endl; cout<<"perimeter of square="<<square.perimeter(); getch(); }
C++ Class Assignments
39
Lecture No- 11 Assignment No- 1
Objective Write a program to calculate product and division using inline function Command to be Used
1. Inline Function
Output:
/* PROGRAM ON INLINE FUNCTION*/ #include<iostream.h> #include<conio.h> inline float mul(float x, float y) { return (x*y); } inline double div(double p,double q) { return (p/q); } void main() { clrscr(); float a=12.345; float b=9.82; cout <<"product:"<< mul(a,b) << endl; cout <<"division:"<< div(a,b) << endl; getch(); }
C++ Class Assignments
40
Lecture No- 11 Assignment No- 2
Objective: Create a class MyClass, declare a variable x and methods get_x(), set_x(int), then create the array of objects for this class and set the values for object & display it Command to be Used
1. Object Array Output
/* Arrays of objects*/ #include<iostream> #include<conio.h> using namespace std; class MyClass { int x; public: void set_x(int i){x=i;} int get_x() {return x;} }; int main() { MyClass obs[4];//creating object array int i; for(i=0;i<4;i++) { obs[i].set_x(i); } for(i=0;i<4;i++) { cout<<"obs["<<i<<"].get_x():"<<obs[i].get_x()<<"\n"; } getch(); return 0; }
C++ Class Assignments
41
Lecture No- 12 Assignment No- 1
Objective: Write a program for overloading unary operator for finding the coordinates of point in space of mirror image Command to be Used
1. Operator Overloading Output:
#include<iostream.h> #include<conio.h> class space { int x; int y; int z; public: void getdata(int a,int b,int c); void display(); void operator-(); }; void space::getdata(int a,int b,int c) { x=a;y=b;z=c; } void space::display() { cout<<"x="<<x<<", y="<<y<<", z="<<z; } void space::operator-() { x=-x; y=-y; z=-z;
C++ Class Assignments
42
} void main() { space s; s.getdata(10,-20,30); clrscr(); cout<<"\ncoordinate of a point in space:\n"; s.display(); -s; cout<<"\ncoordinate of a point in space of mirror image:\n"; s.display(); getch(); }
C++ Class Assignments
43
Lecture No- 12 Assignment No- 2
Objective: Write a program for adding two complex numbers using binary operator overloading. Command to be Used
1. Operator overloading. Output:
#include<iostream.h> #include<conio.h> class complex { float x,y; public: complex(){} complex(float r,float i) { x=r; y=i; } complex operator+(complex); void display() { cout<<x<<"+"<<y<<"i"<<endl; } }; complex complex::operator+(complex c) { complex temp; temp.x=x+c.x; temp.y=y+c.y; return(temp); } void main() {
C++ Class Assignments
44
complex c1,c2,c3; c1=complex(10,20); c2=complex(3,54); c3=c1+c2; clrscr(); cout<<" ";c1.display(); cout<<"+ ";c2.display(); cout<<"-----------"<<endl; cout<<" ";c3.display(); getch(); }
C++ Class Assignments
45
Lecture No- 13 Assignment No- 1
Objective Write a program to define class student with constructor taking id & name as parameter. Also derived class CommerceStudent taking parameter paramter id, name, result (marks) and pass it to base class Command to be Used
2. Inheritance
Output:
#include<iostream.h> #include<conio.h> #include<string.h> class student { int id; char name[20]; public: student(int i,char nm[]) { id=i; strcpy(name,nm); } void dispDetails() { cout<<"\nId :"<<id; cout<<"\nName :"<<name; } }; class CommerceStudent:public student { int res;
C++ Class Assignments
46
public: CommerceStudent(int i,char nm[],int r):student(i,nm) { res=r; } void DisplayResult() { cout<<"\nResult: "<<res; } }; void main() { clrscr(); CommerceStudent C1(1,"Magesh",67); C1.dispDetails(); C1.DisplayResult(); getch(); }
C++ Class Assignments
47
Lecture No- 13 Assignment No- 2
Objective Create a class Cycle and another class bike and derive the characteristic of cycle into bike using inheritance Command to be Used
1. Inheritance
Output:
#include<iostream.h> #include<conio.h> #include<string.h> //single inheritance class Cycle { protected: int tyres; char tyreThickness[20]; char color[10];
C++ Class Assignments
48
char handle[20]; char mechanism[10]; char alert[10]; public: Cycle() { tyres=2; strcpy(tyreThickness,"thin"); strcpy(color,"black"); strcpy(handle,"with brakes"); strcpy(mechanism,"Paddel"); strcpy(alert,"bell"); } void display() { cout<<endl<<"===============Cycle======================"<<endl; cout<<"Tyres:"<<tyres<<endl; cout<<"Tyres width:"<<tyreThickness<<endl; cout<<"Handle:"<<handle<<endl; cout<<"Riding Mechanism:"<<mechanism<<endl; cout<<"Alert:"<<alert<<endl; cout<<"Color:"<<color<<endl; cout<<endl<<"========================================="<<endl; } }; class Bike:Cycle { char engine[20]; char powersupply[10]; public: Bike(char c[10]) { strcpy(color,c); strcpy(handle,"with brakes & accelarator"); strcpy(mechanism,"motor"); strcpy(engine,"4 stroke"); strcpy(tyreThickness,"broad"); strcpy(alert,"Horn"); strcpy(powersupply,"Petrol"); } void display() { cout<<endl<<"===============Bike======================="<<endl; cout<<"Tyres:"<<tyres<<endl; cout<<"Tyres width:"<<tyreThickness<<endl; cout<<"Handle:"<<handle<<endl; cout<<"Riding Mechanism:"<<mechanism<<endl; cout<<"Alert:"<<alert<<endl; cout<<"Color:"<<color<<endl; cout<<"Engine:"<<engine<<endl; cout<<"Power supply:"<<powersupply<<endl; cout<<endl<<"==================================="<<endl;
C++ Class Assignments
49
} }; void main() { Cycle c; clrscr(); c.display(); Bike b("red"); b.display(); getch(); }
C++ Class Assignments
50
Lecture No- 13 Assignment No- 3
Objective Write a program to define a class student and a derived class EnggStudent of student Command to be Used
1. Inheritance Output:
#include<iostream.h> #include<conio.h> #include<string.h> class student { int id; char name[20]; public: void getDetails(int i,char nm[]) { id=i; strcpy(name,nm); } void dispDetails() { cout<<"\nId :"<<id; cout<<"\nName :"<<name; } }; class EnggStudent:public student { int sub1,sub2,sub3,res; public: void getMarks(int s1,int s2,int s3) { sub1=s1; sub2=s2; sub3=s3;
C++ Class Assignments
51
} char DisplayResult() { res=(sub1+sub2+sub3)/3; if(res>=50) return 'P'; else return 'F'; } }; void main() { clrscr(); EnggStudent E1; E1.getDetails(1,"Meena"); E1.dispDetails(); E1.getMarks(78,78,97); char R; R=E1.DisplayResult(); if(R=='P') cout<<"\tPassed"; else if(R=='F') cout<<"\tFail "; else cout<<"\tAbsent"; getch(); }
C++ Class Assignments
52
Lecture No- 13 Assignment No- 4
Objective To write a program for, Hierarchical Inheritance Command to be Used
1. Inheritance
Output:
#include<iostream.h> #include<conio.h> #include<string.h> class student { int id; char name[20]; public: void getDetails(int i,char nm[]) { id=i; strcpy(name,nm); } void dispDetails() { cout<<"\nId :"<<id; cout<<"\nName :"<<name; } }; class EnggStudent:public student { int sub1,sub2,sub3,res; public: void getMarks(int s1,int s2,int s3)
C++ Class Assignments
53
{ sub1=s1; sub2=s2; sub3=s3; } char DisplayResult() { res=(sub1+sub2+sub3)/3; if(res>=50) return 'P'; else return 'F'; } }; class ScienceStudent:public student { int sub1,sub2,sub3,sub4,res; public: void getMarks(int s1,int s2,int s3,int s4) { sub1=s1; sub2=s2; sub3=s3; sub4=s4; } char DisplayResult() { res=(sub1+sub2+sub3+sub4)/4; if(res>=50) return 'P'; else return 'F'; } }; void main() { clrscr(); EnggStudent E1; E1.getDetails(11,"Meena"); E1.dispDetails(); E1.getMarks(78,78,97); char R; R=E1.DisplayResult(); if(R=='P') cout<<"\tPassed"; else if(R=='F') cout<<"\tFail "; else cout<<"\tAbsent"; ScienceStudent S1;
C++ Class Assignments
54
S1.getDetails(12,"Vani"); S1.dispDetails(); S1.getMarks(78,68,77,81); char R1; R1=S1.DisplayResult(); if(R1=='P') cout<<"\tPassed"; else if(R1=='F') cout<<"\tFail "; else cout<<"\tAbsent"; getch(); }
C++ Class Assignments
55
Lecture No- 14 Assignment No- 1
Objective Write a program for to illustrate virtual functions Command to be Used 1. Virtual functions 2. Pointer 3. Reference Operator
Output:
#include <iostream.h> #include<conio.h> class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area ()=0; }; class CRectangle: public CPolygon { public: int area () { return (width * height); } }; class CTriangle: public CPolygon { public: int area () { return (width * height / 2); } };
C++ Class Assignments
56
void main () { clrscr(); CRectangle rect; CTriangle trgl; CPolygon * ppoly1 = ▭ CPolygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout<<"Area of Rectangle :"; cout << ppoly1->area() << endl; cout<<"Area of Triangel :"; cout << ppoly2->area() << endl; getch(); }
C++ Class Assignments
57
Lecture No- 14 Assignment No- 2
Objective Write a program for to illustrate virtual functions Command to be Used 1. Virtual Keyword Output:
#include <iostream.h> #include<conio.h> #include<string.h> class ABC { protected: public: virtual void abc() { cout<<"\nABC class function called..."; } }; class XYZ: public ABC { public: void abc() { cout <<"\nXYZ class function called..."; } }; void main() { clrscr(); ABC *p;
C++ Class Assignments
59
Lecture No- 14 Assignment No- 3
Objective Create a user-defined type AddsTwoIntegers which is a pointer to a function that can take two integers and perform addition Command to be Used
1. type def
Output:
#include <iostream.h> #include <conio.h> int Addition(int a, int b) { return a + b; } int main() { // Creating a programmer-defined type typedef int (*AddTwoIntegers)(int x, int y); AddTwoIntegers TwoNumbers; int x = 128, y = 5055; TwoNumbers = Addition; // Call the pointer to function as if it had been defined already clrscr(); cout << x << " + " << y << " = " << TwoNumbers(x, y); getch(); return 0; }
C++ Class Assignments
60
Lecture No- 15 Assignment No- 1
Objective: Write a program to align the text with equal spacing using manipulators Command to be Used
1. iomanip.h 2. setw()
Output:
#include <iostream.h> #include <iomanip.h> #include<stdlib.h> #include<conio.h> void main( ) { clrscr(); int x1=12345,x2= 23456, x3=7892; cout << setw(8) << "Exforsys" << setw(20) << "Values" << endl; cout<< setw(8) << "E1234567" << setw(20)<< x1 << endl; cout<< setw(8) << "S1234567" << setw(20)<< x2 << endl; cout<< setw(8) << "A1234567" << setw(20)<< x3 << endl; getch(); }
C++ Class Assignments
61
Lecture No- 15 Assignment No- 2
Objective Write a program to set number of decimal to display using setprecision() Command to be Used 1. iomanip.h 2. setprecision()
Output:
#include <iostream.h> #include <iomanip.h> #include<conio.h> void main( ) { clrscr(); float x = 345.9961; cout << "fixed " << setprecision(3) << x << endl; cout << "sceintific "<< x << endl; getch(); }
C++ Class Assignments
62
Lecture No- 16 Assignment No- 1
Objective Write a program to add elements in a Linked List and to Display. Command to be Used
1. Pointers
Output:
#include <iostream.h> #include<conio.h> class linklist { private: struct node { int data; node *link; }*p; public: linklist(); void append( int num );
C++ Class Assignments
63
void add_as_first( int num ); void addafter( int c, int num ); void del( int num ); void display(); int count(); ~linklist(); }; linklist::linklist() { p=NULL; } void linklist::append(int num) { node *q,*t; if( p == NULL ) { p = new node; p->data = num; p->link = NULL; } else { q = p; while( q->link != NULL ) q = q->link; t = new node; t->data = num; t->link = NULL; q->link = t; } } void linklist::add_as_first(int num) { node *q; q = new node; q->data = num; q->link = p; p = q; } void linklist::addafter( int c, int num) { node *q,*t; int i; for(i=0,q=p;i<c;i++) { q = q->link; if( q == NULL )
C++ Class Assignments
64
{ cout<<"\nThere are less than "<<c<<" elements."; return; } } t = new node; t->data = num; t->link = q->link; q->link = t; } void linklist::del( int num ) { node *q,*r; q = p; if( q->data == num ) { p = q->link; delete q; return; } r = q; while( q!=NULL ) { if( q->data == num ) { r->link = q->link; delete q; return; } r = q; q = q->link; } cout<<"\nElement "<<num<<" not Found."; } void linklist::display() { node *q; cout<<endl; for( q = p ; q != NULL ; q = q->link ) cout<<endl<<q->data; } int linklist::count() { node *q; int c=0; for( q=p ; q != NULL ; q = q->link )
C++ Class Assignments
65
c++; return c; } linklist::~linklist() { node *q; if( p == NULL ) return; while( p != NULL ) { q = p->link; delete p; p = q; } } void main() { clrscr(); linklist ll; cout<<"No. of elements = "<<ll.count(); ll.append(12); ll.append(13); ll.append(23); ll.append(43); ll.append(44); ll.append(50); ll.add_as_first(2); ll.add_as_first(1); ll.addafter(3,333); ll.addafter(6,666); ll.display(); cout<<"\nNo. of elements = "<<ll.count(); ll.del(333); ll.del(12); ll.del(98); cout<<"\nNo. of elements = "<<ll.count(); getch(); }
C++ Class Assignments
66
Lecture No- 17 Assignment No- 1
Objective:
Write a program to add text into a File.
Command to be Used
1. ofstream
Output:
/*program on file stream*/ #include<iostream.h> #include<fstream.h> #include<string.h> #include<stdio.h> #include<conio.h> void main() { clrscr(); char string[80]; cout << "Enter a String \n"; gets(string); int len = strlen(string); fstream file; file.open("Test.txt",ios::out | ios::in); for(int i=0; i<len; i++) file.put(string[i]); file.seekg(0); //Moves get pointer(input)to a specified location. char ch; while(file) { file.get(ch); cout << ch; } file.close(); cout << "\nData stored Successfully";
C++ Class Assignments
68
Lecture No- 17 Assignment No- 2
Objective Write a program to accept the no of items and cost and save it in file and read the content of the file to display the no of items and cost. Commands to be used
1. ifstream 2. ofstream
Output
#include<iostream.h> #include<fstream.h> #include<conio.h> void main() { ofstream outf("Items.txt");//connect items file to outf clrscr(); cout<<"Enter item name\n"; char name[30]; cin>>name; outf<<name<<"\n";//write to file cout<<"enter item cost:"; float cost; cin>>cost; outf<<cost<<"\n"; outf.close(); ifstream inf("items.txt"); inf>>name; inf>>cost; cout<<"\n"; cout<<"items name:"<<name<<endl; cout<<"item cost:"<<cost; inf.close(); getch(); }
C++ Class Assignments
69
Lecture No- 18 Assignment No- 1
Objective Write a program, using template to Display Values Command to be Used Template class Output:
/* PROGRAME RELATED TO TEMPLATE*/ #include<iostream.h> #include<conio.h> template <class T1, class T2> void Function(T1 x, T2 y) { cout << x << "\t" << y << endl; } void main() { clrscr(); Function(10,20); Function(10.5,12.5); Function('I','J'); getch(); }
C++ Class Assignments
70
Lecture No- 18 Assignment No- 2
Objective Write a program sorting using Template Function Command to be Used
1. Template Output:
/*PROGRAME RELATED TO TEMPLATE */ #include<iostream.h> #include<conio.h> template<class T1, class T2> class MyClass { private: T1 i; T2 j,c; public: void Put(); void Get(); T2 Multi(); }; template<class T1, class T2> void MyClass<T1,T2>::Put() { cout << "The Product is : " << c << endl; } template<class T1, class T2> void MyClass<T1,T2>::Get() { cout << "Enter the value of x : ";