Anda di halaman 1dari 80

CS2312

OBJECT ORIENTED PROGRAMMING LAB

LTPC 0032

Aim: To develop object-oriented programming skills using C++ and Java.

1. Function overloading, default arguments in C++ 2. Simple class design in C++, namespaces, objects creations 3. Class design in C++ using dynamic memory allocation, destructor, copy constructor 4. Operator overloading, friend functions 5. Overloading assignment operator, type conversions 6. Inheritance, run-time polymorphism 7. Template design in C++ 8. I/O, Throwing and Catching exceptions 9. Program development using STL 10. Simple class designs in Java with Javadoc 11. Designing Packages with Javadoc comments 12. Interfaces and Inheritance in Java 13. Exceptions handling in Java 14. Java I/O 15. Design of multi-threaded programs in Java

TOTAL: 45 PERIODS

~1~

PKS

Programming using C++

~2~

Output: Volume of Cube :1000

Volume of Cuboid :1004.94 Volume of Cylinder:2795.92

Viva questions: 1. What are the features of OOP? When a program termed to be OO Program?

2. Define Function Overloading

3. Give prototype for Function Overloading

4. Brief default parameters available in exercise

~3~

Ex. No. : 1 Function overloading, default arguments in C++

Aim: To implement calculation for volume of Cube, Cuboids and Cylinder through Function Overloading and also passing Default arguments in C++. Algorithm: Step 1: Defining the variable and function for cube, cuboids and cylinder. Step 2: Declaring the function with one argument for cube and return type as integer. Step 3: Declaring the function with three argument length, breadth, and height for cuboids with return type double. Step 4: Declaring the function with two argument radius and height for cylinder with return type double. Step 5: Calling the declared function with parameter value for cube, cuboid and cylinder. Step 6: Print the return value. Step 7: Stop the process. Program: #include<iostream.h> #include<conio.h> int volume(int); double volume (int, double, int h = 9); double volume (double, int h = 8); float pi=3.14; int volume (int a) { return (a*a*a); } double volume (int l, double b, int h) { return (l*b*h); } double volume (double r, int h) { return (pi*r*r*h); }

// Volume of cube // Volume of Cuboids // Volume of Cylinder //Implementation of above definition

~4~

5. Write a program for area of circle, rectangle and triangle using function overloading

6. Write a program to demonstrate function overloading is carried out for swapping of two variables of the various data types, namely integer, floating point number and character.

Result: Thus, Volume of Cube, Cuboids and Cylinder was calculated using Function Overloading and Default arguments.

~5~

int main() { cout<<"Volume of Cube :"<<volume(10)<<endl; // Function Call for Cube cout<<"Volume of Cuboid :"<<volume(20, 5.583)<<endl;// Function Call for Cuboids cout<<"Volume of Cylinder:"<<volume(10.55)<<endl; // Function Call for Cylinder return 0; }

~6~

Output: Simple Class design Enter the values a &b: 78 96 C = 174 Average=87

Viva questions: 1. Define namespace

2. Give prototype for Class and creation of object

3. Brief use of data member and function in exercise

~7~

Ex. No. : 2

Simple class design in C++, namespaces, objects creations

Aim: To implement the class with namespaces, object creations in C++. Algorithm: Step 1: Defining the namespace, class, variable and function. Step 2: Declaring the function getdata and enter the two values for variable. Step 3: Declaring the function sum for performing adding operation. Step 4: Declaring the function display then print the added value. Step 5: Creating the object for a class and calling the functions by object variable. Step 6: Stop the process. Program: #include<iostream.h> using namespace std; namespacevalD { int t=2; } class add { inta,b,c;

// Declare members to class Add

public: voidgetdata(void); // Declare member functions to class Add voidsumavg(void); void display(void); }; void add::getdata(void) // Collect the data { cout<<"Enter the values a & b: "; cin>>a>>b; } void add::sumavg(void) // Sum the data values { c=a+b; }

~8~

4. Write a program to declare a integer, float and character in different namespace and use it

5. Write aSimple Class Example Program to checka number is Prime or not

Result: Thus the implementation of class with namespaces and creating object are executed successfully.

~9~

void add::display(void) // Display the data { cout<<"C = "<<c; cout<<endl<<"Average= "<<c/(valD::t)<<endl;// Using of name space value } int main() { add a; cout<<"Simple Class design"<<endl; a.getdata(); a.sumavg(); a.display(); return 0; }

~ 10 ~

Output: Enter rows and cols of the matrix... 3 3

Enter the matrix elements one by one...5 5 5 5 5 5 5 5 5

Entered matrix is... 5 5 5 5 5 5 5 5 5

Copy constructor invoked...

Result of copy constructor is... 5 5 5 5 5 5 5 5 5

Destructor invoked...

Destructor invoked...

~ 11 ~

Ex. No. : 3

Class design in C++ using dynamic memory allocation, destructor, copy constructor

Aim: To implement class with the dynamic memory allocation of construct a matrix, destructor and copy constructor using C++. Algorithm: Step 1: Defining the namespace, class and variable. Step 2: Declaring the class matrix along with the constructor and destructor. Step 3: Constructor with no argument which assign the value for row and column as null. Step 4: Constructor with two argument are the function are declared. Step 5: The values are copied to another matrix. Step 6: De-allocate the memory after copying the matrix. Step 7: Stop the process. Program: #include<iostream.h> using namespace std; class matrix { int **m; int row, col; public: matrix() { row=col=0; m=NULL; } matrix(int r ,int c); ~matrix(); voidgetmatrix(); voidshowmatrix(); matrix(matrix &m2); }; // Two argument Constructor // Destructor // Collect value // Display & delete matrix memory //copy constructor

~ 12 ~

Viva questions: 1. Define dynamic memory allocation

2. What is Constructor? When it will be invoked? Give Prototype for multiple arguments Constructor?

3. What is Destructor?When it will be invoked? Give Prototype for Destructor?

4. What is need for Copy Constructor? Give prototype for Copy Constructor

5. Compare features of Constructors and Destructors.

~ 13 ~

matrix::~matrix() { cout<<"\nDestructor invoked...\n"; for(inti=0;i<row;i++) delete m[i]; delete m; } matrix::matrix(int r ,int c) { row = r; col = c; m = new int*[row]; for(inti=0;i<row;i++) m[i]=new int[col]; }

//Free memory space

//Memory allocation of r X c

matrix::matrix(matrix &m2) { cout<<"\nCopy constructor invoked...\n"; row = m2.row; col = m2.col; m = new int*[row]; for(inti=0;i<row;i++) m[i]=new int[col]; for(inti=0;i<row;i++) for(int j=0;j<row;j++) m[i][j]=m2.m[i][j]; //CopyingMatrix } void matrix::getmatrix() { for(inti=0;i<row;i++) for(int j=0; j<col; j++) cin>>m[i][j]; } void matrix::showmatrix() { for(inti=0;i<row;i++) { for(int j=0;j<col;j++) cout<<"\t"<<m[i][j]; cout<<"\n"; } }

//Collect matrix input

//Display Matrix

~ 14 ~

6. Write a Program using above code create two matrices A and B and perform addition display it

Result: Thus implementation of dynamic memory allocation of construct a matrix, destructor and copy constructor are executed successfully.

~ 15 ~

int main() { intr,c; cout<<"\nEnter rows and cols of the matrix...\n"; cin>>r>>c; matrix m1(r,c); cout<<"\nEnter the matrix elements one by one..."; m1.getmatrix(); cout<<"\nEntered matrix is...\n"; m1.showmatrix(); //Invoking copy constructor matrix m2=m1; cout<<"\nResult of copy constructor is...\n"; m2.showmatrix(); return 0; }

~ 16 ~

Output: Before operator overloading I : Longitude :10 Latitude :20

II : Longitude :5 Latitude :30

After overloading binary operator +: Longitude :15 Latitude :50

After overloading binary operator -: Longitude :10 Latitude :20

After overloading unary operator ++: Longitude :11 Latitude :21

After overloading unary operator ++: Longitude :12 Latitude :22

Viva questions: 1. What is need for Operator overloading? Give prototype for Operator overloading

2. What is need for Friend function? Give prototype for Friend function

3. Give prototype for Friend class

4. What are operators cannot be overloaded ?

~ 17 ~

Ex. No. : 4

Operator overloading, friend functions

Aim: To implement Longitude and Latitude value based operation using operator overloading and friend functions using C++. Algorithm: Step 1: Defining the namespace, class, variable and function. Step 2: Constructor with two arguments for assigning the longitude and latitude values. Step 3: Declaring the friend function with operator overloading. Step 4: Declaring the show function, displays the operator overloaded values. Step 5: Creating the object for a class and calling the functions by object variable for unary, binary overloading operation. Step 6: Stop the process. Program: #include<iostream.h> using namespace std; class loc { intlongitude,latitude; public: loc() { } loc(intlg, intlt) { longitude=lg; latitude=lt; } void show() { cout<<" Longitude :"<<longitude<<" Latitude :"<<latitude<<endl; } friendloc operator +(loc op1,loc op2); // Add two longitude and latitude friendloc operator -(loc op1,loc op2); // Subtract two longitude and latitude friendloc operator ++(loc&op1); // Increment longitude and latitude };

~ 18 ~

5. Give prototype for Unary and Binary operator overloading

6. Write a Program to create collect two complex number and perform addition, subtraction

Result: Thus the implementation of operator overloading and friend function executed successfully.

~ 19 ~

loc operator +(loc op1,loc op2) { loc temp; temp.longitude=op1.longitude+op2.longitude; temp.latitude=op1.latitude+op2.latitude; return temp; } loc operator -(loc op1,loc op2) { loc temp; temp.longitude=op1.longitude-op2.longitude; temp.latitude=op1.latitude-op2.latitude; return temp; } loc operator++(loc &op1) { op1.longitude ++; op1.latitude ++; return op1; } int main() { loc ob1(10,20),ob2(5,30); cout<<"\nBefore operator overloading" <<endl<<"I :"; ob1.show(); cout<<endl<<"II :"; ob2.show(); ob1=ob1+ob2; cout<<"\nAfter overloading binary operator +:"; ob1.show(); ob1=ob1-ob2; cout<<"\nAfter overloading binary operator -:"; ob1.show(); ++ob1; cout<<"\nAfter overloading unary operator ++:"; ob1.show(); ob2=++ob1; cout<<"\nAfter overloading unary operator ++:"; ob2.show(); return 0; }

~ 20 ~

Output: c1= 5+10i c2= 50+100i c2 with += increment of c1: c2= 55+110i

Assign c2 to c3: c3= 55+110i c4= 10+50i c3 with -= decrement of c4 c3= 45+60i

~ 21 ~

Ex. No. : 5

Overloading assignment operator, type conversions

Aim: To implement assignment operator overloading and type conversions are using C++. Algorithm: Step 1: Defining the namespace, class, variable and function. Step 2: Constructor with two arguments for assigning the real and imaginary values in complex number. Step 3: Declaring the function with assignment operator overloading. Step 4: Passing the values in the calling function argument for complex number. Step 5: The incremented values are copied to another complex number. Step 6: The decrement operation are performed with the copied complex number using the assignment operator. Step 7: Stop the process.

Program: #include<iostream.h> using namespace std; classMyComplex { private: double real, imag; public: MyComplex() { real = 0; imag = 0; } MyComplex(double r, double i) { real = r; imag = i; }

// Constructor declaration

// Constructor invoked with parameters

~ 22 ~

Viva questions:

1. Give prototype for Assignment Operator overloading

2. Compare the Operator and Assignment Operator overloading

3. Is default value is exist in declaration or not ?

4. Compare the Binary and Assignment operator overloading

~ 23 ~

doublegetReal() { return real; } doublegetImag() { returnimag; } MyComplex& operator=(MyComplex&);// Assignment of complex numbers MyComplex& operator+=(MyComplex& );// Increment of one with another complex MyComplex& operator-=(MyComplex& );// Decrement of one with another complex }; MyComplex&MyComplex::operator = (MyComplex& c) { this->real = c.real; this->imag = c.imag; return *this; } MyComplex&MyComplex::operator += (MyComplex& c) { this->real += c.real; this->imag += c.imag; return *this; } MyComplex&MyComplex::operator -= (MyComplex& c) { this->real -= c.real; this->imag -= c.imag; return *this; } int main() { MyComplexc1(5,10); MyComplexc2(50,100); cout<< "c1= " << c1.getReal() << "+" << c1.getImag() << "i" <<endl; cout<< "c2= " << c2.getReal() << "+" << c2.getImag() << "i" <<endl; c2 += c1; cout<< "c2 with += increment of c1:" <<endl; cout<< "c2= " << c2.getReal() << "+" << c2.getImag() << "i" <<endl; cout<<endl; MyComplex c3;

~ 24 ~

5. Write a Program to create collect two matrix and perform addition, subtraction

Result: Thus the implementation of assignment operator overloading and type conversions are executed successfully.

~ 25 ~

c3 = c2; cout<< "Assign c2 to c3:" <<endl; cout<< "c3= " << c3.getReal() << "+" << c3.getImag() << "i" <<endl; MyComplexc4(10,50); cout<< "c4= " << c4.getReal() << "+" << c4.getImag() << "i" <<endl; c3 -= c4; cout<< "c3 with -= decrement of c4" <<endl; cout<< "c3= " << c3.getReal() << "+" << c3.getImag() << "i" <<endl; }

~ 26 ~

Output: Enter your A/c no.:15421 Account Number : 15421 Enter the A/c type, 1.Savings 2.Current 3.Exit 1 Enter the A/c type, 1.Deposit 2.Withdraw 1 Enter the amount to be deposited = Rs.21545 Your A/c Balance is=Rs.21545 Account Number : 15421 Enter the A/c type, 1.Savings 2.Current 3.Exit 1 Enter the A/c type, 1.Deposit 2.Withdraw 2 Enter the amount to be withdrawn = Rs.254 Your A/c Balance is=Rs.21291 Account Number : 15421 Enter the A/c type, 1.Savings 2.Current 3.Exit 2 Last amount withdrawn=Rs.254 Last amount deposited=Rs.21545 Your A/c Balance is=Rs.21291 Account Number : 15421 Enter the A/c type, 1.Savings 2.Current 3.Exit 3

~ 27 ~

Ex. No. : 6

Inheritance, run-time polymorphism

Aim: To implement the inheritance and run-time polymorphism using C++. Algorithm: Step 1: Defining the namespace, class, variable and function. Step 2: Class bank displays the customer name and account number. Step 3: Inherit properties of the class bank in newly created class savings. Step 4: Class savings to perform the deposit and withdraw process. Step 5: Class current inherits with class savings to display the account information. Step 6: By creating the object for a class currentall the values are accessed and calling the functions by object variable for performing banking operation. Step 7: Stop the process. Program: #include<iostream.h> using namespace std; class bank // Create Bank Base Class { public: //Bank account Number longintacno; virtual void display() { cout<<Account Number :<<acno; } }; class savings : public bank // Create derived class Savings using Bank Base Class { public: intwdraw=0, dep=0, bal=0; void saves() { intch; cout<<"Enter the A/c type,1.Deposit 2.Withdraw\n"; cin>>ch;

~ 28 ~

Viva questions: 1. Define inheritance

2. What are types of inheritance

3. Compare inheritance and run-time polymorphism

4. Write a Program to collect student details of mark using Multilevel Inheritance

~ 29 ~

switch(ch) { case 1: cout<<"Enter the amount to be deposited = Rs."; cin>>dep; bal+=dep; cout<<"Your A/c Balance is=Rs."<<bal<<endl; break; case 2: cout<<"Enter the amount to be withdrawn = Rs."; cin>>wdraw; bal-=wdraw; cout<<"Your A/c Balance is=Rs."<<bal<<endl; break; default: cout<<"Invalid Choice"; break; } } }; class current : public savings // Create derived class Savings using Bank Base Class { public: voiddisplay() { cout<<"Last amount withdrawn=Rs."<<wdraw<<endl; cout<<"Last amount deposited=Rs."<<dep<<endl; cout<<"Your A/c Balance is=Rs."<<bal<<endl; } }; int main() { intch; current ac; cout<<endl<<"Enter your A/c no.:"; cin>>ac.acno; cout<<endl; while(1) { Cout<<endl<<Account Number : <<acno<<endl; cout<<"Enter the A/c type,1.Savings 2.Current 3.Exit\n"; cin>>ch;

~ 30 ~

5. Write a Program to maintain book lending to staff and students using Multiple Inheritance

Result: Thus the implementation of inheritance and run time polymorphism are executed successfully.

~ 31 ~

switch(ch) { case 1: ac.saves(); break; case 2: ac.display(); break; case 3: break; default: cout<<"Invalid Choice"; break; } if (ch==3) break; } }

~ 32 ~

Output: Bubble SORT

1.Integer Sort

2.Float Sort

3.Character Sort

4.Exit

Enter Ur choice:1

Bubble Sort on Integer Values... Enter the size of array: 4

Enter the array elements:85 68 45 21

The sorted array is... 21 45 68 85

Bubble SORT

1.Integer Sort

2.Float Sort

3.Character Sort

4.Exit

Enter Ur choice:2

Bubble Sort on Float Values... Enter the size of array: 4

Enter the array elements:5.665532 3.24541 8.456541 4.56646665

~ 33 ~

Ex. No. : 7

Template design in C++

Aim: To implement the template design using C++ Algorithm: Step 1: Defining the namespace, class, variable and function. Step 2: Declaring the template class T. Step 3: Declaring the get function for getting the value to bubble sort. Step 4: Declaring the display function to display the value before bubble sorting. Step 5: Declaring the sort function for bubble sorting process. Step 6: The integer, float and character are bubble sorted. Step 7: Separate object are created for bubble sorting integer, float and character. Step 8: Stop the process. Program: #include<iostream.h> #include<iomanip> using namespace std; template<class t> class bubble { t a[25]; public: void get(int); void sort(int); void display(int); }; template<class t> void bubble <t>::get(int n) { inti; cout<<"\nEnter the array elements:"; for(i=0;i<n;i++) cin>>a[i]; } // Create template class

// Declare template variable // Definition for collect values // Definition for sort values // Definition for display sorted values

~ 34 ~

The sorted array is... 3.24541 4.56647 5.66553 8.45654 Bubble SORT

1.Integer Sort

2.Float Sort

3.Character Sort

4.Exit

Enter Ur choice:3

Bubble Sort on Character Values... Enter the size of array: 4

Enter the array elements:p a s d

The sorted array is... a d p s

Bubble SORT

1.Integer Sort

2.Float Sort

3.Character Sort

4.Exit

Enter Ur choice:4

~ 35 ~

template<class t> void bubble <t>::display(int n) { inti; cout<<"\nThe sorted array is...\n"; for(i=0;i<n;i++) cout<<a[i]<<setw(10); } template<class t> void bubble <t>::sort(int n) { inti,j; t temp; for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(a[i]>a[j]) // Comparing values and interchanging it { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } } int main() { bubble<int>obj1; //Initialize integer list for template collection bubble<float>obj2; //Initialize Float list for template collection bubble<char>obj3; //Initialize Character list for template collection intw,n; do { cout<<"\nBubble SORT\n"; cout<<"\n1.Integer Sort\t2.Float Sort\t3.Character Sort\t4.Exit\n"; cout<<"\nEnter Ur choice:"; cin>>w; switch(w) { case 1: cout<<"\nBubble Sort on Integer Values..."; cout<<"\nEnter the size of array:\n"; cin>>n; obj1.get(n); obj1.sort(n); obj1.display(n); break;

~ 36 ~

Viva questions: 1. Define Template

2. Compare Class and Template

3. Classify features of template member with class member

4. Can we use friend member function for template? If so How?

5. Can we use constructor in template? If so How?

Result: Thus the implementation of Template executed successfully.

~ 37 ~

case 2: cout<<"\nBubble Sort on Float Values..."; cout<<"\nEnter the size of array:\n"; cin>>n; obj2.get(n); obj2.sort(n); obj2.display(n); break; case 3: cout<<"\nBubble Sort on Character Values..."; cout<<"\nEnter the size of array:\n"; cin>>n; obj3.get(n); obj3.sort(n); obj3.display(n); break; case 4: break; default: cout<<"Invalid Choice\n"; break; } }while(w!=4); }

~ 38 ~

Output: STACK

1.Push

2.Pop 3.Display

4.Exit

ENTER THE CHOICE:1

Enter Number to Push:56

Top element in stack is:56

1.Push

2.Pop 3.Display

4.Exit

ENTER THE CHOICE:1

Enter Number to Push:78

Top element in stack is:78

1.Push

2.Pop 3.Display

4.Exit

ENTER THE CHOICE:1

Enter Number to Push:99

Top element in stack is:99

1.Push

2.Pop 3.Display

4.Exit

ENTER THE CHOICE:1

Enter Number to Push:23

Top element in stack is:23

~ 39 ~

Ex. No. : 8

I/O, Throwing and Catching exceptions

Aim: To implement the I/O, Throwing and Catching Exceptions using C++. Algorithm: Step 1: Defining the namespace, class, variable and function. Step 2:Declaring the function for push, pop, and display operation. Step 3:In push function the stack is full it return x=1, otherwise it gets the number and push into the stack. Step 4:In pop function the stack is empty it return x=-1, otherwise it removes the number from top of stack Step 5: By selecting the operation that will performed on the stack Step 6: The values in stack are displayed by selecting the display option. Step 7: Stop the process using exit. Program: #include<iostream.h> #include<iomanip> using namespace std; template<class t> class bubble { #include<iostream.h> using namespace std; classstk { intx,top=-1; int stack[5]; public: int push(); int pop(); int display(); }; // Declare a stack class //Stack pointer initialize with -1 // Integer type stack is created with size of 5 // Stack push operation with return type // Stack pop operation with return type // Display Stack contents with return type

~ 40 ~

1.Push

2.Pop 3.Display

4.Exit

ENTER THE CHOICE:1

Enter Number to Push:55

Top element in stack is:55

1.Push

2.Pop 3.Display

4.Exit

ENTER THE CHOICE:3

CONTENTS OF STACK: 55 23 99 78 56

1.Push

2.Pop 3.Display

4.Exit

ENTER THE CHOICE:1 An exception occurred! Stack is Full

1.Push

2.Pop 3.Display

4.Exit

ENTER THE CHOICE:2

Popped element from Stack is55

1.Push

2.Pop 3.Display

4.Exit

ENTER THE CHOICE:2

Popped element from Stack is23

~ 41 ~

intstk::push() { int x = 0; if(top==5-1) x=1; else { top=top+1; cout<<"\nEnter Number to Push:"; cin>>x; stack[top]=x; cout<<"\nTop element in stack is:"<<x; } return x; }

// Sends message via x to say Stack Full

intstk::pop() { int x = 0; if(top==-1) x=-1; else { x=stack[top]; top=top-1; cout<<"\nPopped element from Stack is"<<x; } return x; // Sends message via x to say Stack empty } intstk::display() { int x = 0; if(top==-1) x=-1; else { cout<<"\nCONTENTS OF STACK:"; for(inti=top;i>=0;i--) { cout<<"\n"<<stack[i]<<"\t"; } } return x; }

// Sends message via x to say Stack empty

~ 42 ~

1.Push

2.Pop 3.Display

4.Exit

ENTER THE CHOICE:2

Popped element from Stack is99

1.Push

2.Pop 3.Display

4.Exit

ENTER THE CHOICE:2

Popped element from Stack is78

1.Push

2.Pop 3.Display

4.Exit

ENTER THE CHOICE:2

Popped element from Stack is56

1.Push

2.Pop 3.Display

4.Exit

ENTER THE CHOICE:2 An exception occurred! Stack is Empty

1.Push

2.Pop 3.Display

4.Exit

ENTER THE CHOICE:3 An exception occurred! Stack is Empty

1.Push

2.Pop 3.Display

4.Exit

ENTER THE CHOICE:4

~ 43 ~

int main() { stk s; int a; cout<<"\nSTACK"; do { intcval=0; // Parameter to receive message from member function cout<<"\n\n1.Push \t2.Pop \t3.Display \t4.Exit"; cout<<"\nENTER THE CHOICE:"; cin>>a; switch(a) { case 1: cval=s.push(); break; case 2: cval=s.pop(); break; case 3: cval=s.display(); break; case 4: break; default: cout<<"\nInvalid Choice"; } try { if (cval == 1 ) // Message for stack full is obtain & initialize throws { throw 5; } if ( cval == -1 ) // Message for stack empty is obtain & initialize throws { throw 1.1f; } } catch (int a) // Message for stack full is catched { cout<<"An exception occurred!" <<endl; cout<<"Stack is Full"<<endl; }

~ 44 ~

Viva questions: 1. What is need for exception handling

2. Write prototype for exception handling

3. How many catches and throws use for a try ?

4. Write a program for Array bound exception

5. Write a program for handling divide by zero

Result: Thus the implementation of I/O, Throwing and Catching exceptions are executed successfully.

~ 45 ~

catch (float b) // Message for stack full is catched { cout<< "An exception occurred!" <<endl; cout<< "Stack is Empty"<<endl; } }while(a<4); }

~ 46 ~

Input (test.txt): File Types of access Parameter mode detailed

Output: File Types of access Parameter mode detailed

Viva questions: 1. Write a program using files to handle exceptions

2. What are different modes for accessing files

3. List some STL features available

4. Can we create a STL on our own?

Result: Thus the implementation of file operation executed successfully.

~ 47 ~

Ex. No. : 9

Program development using STL File Operation

Aim: To implement the file operation using C++. Algorithm: Step 1: Declaring the header file file.h Step 2:Declaring the file output stream Step 3: Open the file in append mode Step 4: Add content to file through stream Step 5: Close the file in write mode Step 6:Declaring the file input stream Step 7: Open the file read mode Step 8: Get content from file through stream and print it Step 9: Close the file in write mode Step 10: Stop the process using exit. Program: #include<iostream.h> #include<fstream> using namespace std; int main () { string line; ofstream myfile1 ("test.txt", ofstream::app); if(myfile1.is_open()) { myfile1 << "\nFile Types of access"; myfile1 << "\nParameter mode detailed"; myfile1.close(); } else cout<< "Unable to open file"; ifstreammyfile ("test.txt"); if (myfile.is_open()){ while ( myfile.good() ) { getline (myfile,line); cout<< line <<endl; } myfile.close(); } elsecout<< "Unable to open file"; return 0; }

// File opened in append mode to write

// File opened in append mode to read

~ 48 ~

~ 49 ~

Programming using Java

~ 50 ~

Output: Generating 10 random integers in range 0..99. Random No is 60 Random No is 79 Random No is 31 Random No is 62 Random No is 6 Random No is 79 Random No is 1 Random No is 26 Random No is 76 Random No is 28

Viva questions: 1. List some packages and its operation

2. Compare STL and Java package

3. What are types of data types can be generated randomly?

4. Is Java partially object oriented or fully object oriented? How ?

Result: Thus the implementation of file operation executed successfully. .

~ 51 ~

Ex. No. : 10

Simple class designs in Java with Javadoc

Aim: To implement class with usage of random number generation using java. Algorithm: Step 1: Declare the class and variable. Step 2: To generate the random number from 0.99 using RandomGenerator. Step 3: Limiting the number range by passing the value to the functionnextInt. Step 4: Display the random number. Step 5: Stop the process.

Program: importjava.util.Random; public final class l10 { public static final void main(String[] Args) { System.out.println("Generating 10 random integers in range 0..99."); Random randomGenerator = new Random(); for (int n = 1; n <= 10; ++n) { intrn = randomGenerator.nextInt(100); System.out.println("Random No is " + rn); } } }

~ 52 ~

Output: Number Serious Generation 7 Factorial is 5040 Fibonacci Serious 0, 1, 1,2,3,5,8,13

Viva questions: 1. Design a package for banking operations

~ 53 ~

Ex. No. :11

Designing Packages with Javadoc comments

Aim: To implement design of packages and utilize using java. Algorithm: Step 1: Declaring the package L11pack, class L11numman and function Step 2:Enter the value for Number Serious Generation Step 3: Import the package L11pack Step 3: Passing the value as parameter for Factorial number and Fibonacci series Step 4: The generated series are displayed Step 5: Stop the process

Program: // Liinumman.java package L11pack; public class L11numman { public void factorial(int n) { int f=1; if(n==0) { System.out.println("Factorial is 1"); } else { for(inti=1; i<=n; i++) { f*=i; } System.out.println("Factorial is "+f); } } // Package Declaration

~ 54 ~

2. Design a package for library lending operations

3. Write prototype for package declaration and accessing it

Result: Thus the implementation of package design using java .

~ 55 ~

public void fibonci(int n) { int f1=0, f2=1; System.out.println("Fibonacci Serious "); if(n>=0) { System.out.print("0"); } if(n>=1) { System.out.print(", 1"); } if(n>=2) { for(inti=2; i<=n; i++) { int x = f2; f2+=f1; System.out.print(","+f2); f1=x; } } } } //l11.java import L11pack.L11numman; importjava.util.Scanner; // Importing of our package

public final class l11 { public static final void main(String[] Args) { System.out.println("Number Serious Generation"); L11numman ln = new L11numman(); Scanner ir= new Scanner(System.in); int number = ir.nextInt(); ln.factorial(number); ln.fibonci(number); } }

~ 56 ~

Output: Enter Rectangle length and width : 10 5 Area of Rectangle =50.0 Circle Radius : 6 Area of Circle =113.04

Viva questions: 1. What is need for interface?

2. What is inheritance?

3. What are types of inheritance? Give it in pictorial form.

4. Write prototype for interface and implementing interface.

5. How to create multiple inheritance in Java ?

~ 57 ~

Ex. No. : 12

Interfaces and Inheritance in Java

Aim: To implement the interface and inheritance using java. Algorithm: Step 1: Define the interface area. Step 2: Implement the interface are to the class rectangle and circle. Step 3: Inherit the rectangle and circle by using the interface. Step 4: Entering the length, breadth and radius total area for rectangle and circle are calculate. Step 4: By creating the objects the area of the rectangle and circle are Displayed. Step 5: Stop the process. Program: // Area.java interface Area { final static float pi=3.14F; float compute(float x,float y); } //Rectangle.java class Rectangle implements Area { public float compute(float x,float y) { return(x*y); } } //Circle.java class Circle implements Area { public float compute(float x, float y) { return(pi*x*x); } }

~ 58 ~

6. Write a interface for sorting and implement bubble and selection sort

Result: Thus the implementation of interfacing and inheritance are executed successfully in java. .

~ 59 ~

// l12.java class l12 { public static void main(String args[]) { Rectangle rect=new Rectangle(); Circle cir=new Circle(); Area ar; ar=rect; Scanner ir= new Scanner(System.in); System.out.println("Enter Rectangle length and width :"); int x = ir.nextInt(); int y = ir.nextInt(); System.out.println("Area of Rectangle ="+ar.compute(x,y)); ar=cir; System.out.println("Circle Radius :"); int r = ir.nextInt(); System.out.println("Area of Circle ="+ar.compute(r,0)); } }

~ 60 ~

Output: Oops, we went to far, better go back to 0!3 Next Process Cannot Divide by Zero!

Viva questions: 1. Write prototype for Exception handling

2. What are default exception available

3. Compare difference between C++ and Java exception handling

4. Write a program to find IO exception

~ 61 ~

Ex. No. :13

Exceptions handling in Java

Aim: To implement the Exception handling using java. Algorithm: Step 1: Declare the class. Step 2: Define the variables. Step 3: By the single try, catch and finally block for handling array out of exception. Step 4: By using single try and multiple catch block handles many exception. Step 5: Stop the process Program: public class l13 { public static void main(String[] args) { int[] array = new int[3]; try { for(inti=0;i<=3;++i) { array[i] = i; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Oops, we went to far, better go back to 0!" + e.getMessage()); } finally { System.out.println("Next Process"); //method call to continue program }

~ 62 ~

5. Write a program to find Class not found exception

Result: Thus the implementation of java exception handling executed successfully.

~ 63 ~

try { array[0] = 2/0; } catch(ArithmeticException e) { System.out.println("Cannot Divide by Zero!"); } catch(Exception e) { System.out.println("An Unknown Error has Occured"); } } }

~ 64 ~

Input: Hai Basic demo for File Manipulation with streams exit

Output: Hai Basic demo for File Manipulation with streams

Viva questions: 1. Write a program using files to handle exceptions

2. What are different modes for accessing files

~ 65 ~

Ex. No. : 14

Java I/O

Aim: To implement the Java input and output for file based using java. Algorithm: Step 1: Declaring class and variables. Step 2: Read the input and write in input text file in bytes until exit String is not input. Step 3: Read the input file in bytes and display it. Step 4: In each read and write operation the file must be open and close properly. Step 5: Stop the process. Program: import java.io.*; importjava.util.Scanner; public class l13 { public static void main (String args[]) throws Exception { String src = ""; String s; do { Scanner in = new Scanner(System.in); s = in.nextLine(); src += s; }while(!(s.equals("exit"))); bytebuf[] = src.getBytes(); OutputStream f1 = new FileOutputStream("input.txt"); f1.write(buf); f1.close();

~ 66 ~

3. Write a program using reader and writer class to perform file operation

4. What are different streamsfor file operations

Result: Thus the implementation of file operation executed successfully. .

~ 67 ~

InputStreaminputStream = new FileInputStream("input.txt"); Reader reader = new InputStreamReader(inputStream); int data = reader.read(); while(data != -1) { chartheChar = (char) data; data = reader.read(); System.out.print(theChar); } reader.close(); } }

~ 68 ~

Output (Run 1): Run method: Thread 1 Run method: 2nd Thread Run method: Thread 1 Run method: 2nd Thread Run method: Thread 1 Run method: 2nd Thread Run method: Thread 1 Run method: Thread 1 Run method: 2nd Thread Run method: 2nd Thread Run method: Thread 1 Run method: 2nd Thread

Output (Run 2):

Run method: 2nd Thread Run method: Thread 1 Run method: 2nd Thread Run method: 2nd Thread Run method: Thread 1 Run method: Thread 1 Run method: Thread 1 Run method: Thread 1 Run method: 2nd Thread Run method: Thread 1 Run method: 2nd Thread Run method: 2nd Thread

~ 69 ~

Ex. No. :15

Design of multi-threaded programs in Java

Aim: To implement the multi-threading using Java. Algorithm: Step 1: Declare the class with extended thread. Step 2: Define the variables. Step 3: Multi-Threads are handled by the declared package. Step 4: By using try and catch interrupted exception are handled. Step 5: Stop the process. Program: //ThreadClass.java Package l15pack; public class ThreadClass extends Thread { String msg; public void run() { for(inti=0;i<=5;i++) { System.out.println("Run method: "+msg); try { sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) { System.out.println("Error : "+e.getMessage()); } } } ThreadClass(String mg) { msg=mg; } }

~ 70 ~

Viva questions: 1. What are differences between wait and sleep method in java

2. How will you awake a blocked thread in java?

3. What is the difference between Process and Thread?

4. What are different states in lifecycle of Thread?

5. What do you understand about Thread Priority?

Result: Thus the implementation of multi-threading executed successfully.

~ 71 ~

//l15.java class l15 { public static void main(String[] args) { ThreadClass dt1=new ThreadClass("Thread 1"); ThreadClass dt2=new ThreadClass("2nd Thread"); dt1.start(); // this will start thread of object 1 dt2.start(); // this will start thread of object 2 } }

~ 72 ~

Additional Exercise for Practice


C++:
1. Write a Program For Simple Class Example Program to Prime Number or not. 2. Write a C++ program for Students mark analysis using Static Data member, Default Argument and Friend Function. 3. Write a C++ program for Students mark analysis using Static Data member, Default Argument and Friend Function. 4. Design C++ classes with static members, methods with default arguments, friend functions. (For example, design matrix and vector classes with static allocation, and a friend function to do matrix-vector multiplication) 5. Write a Program for Addition of two distances of different object using Friend Function in C++ 6. Write a Program for Maximum of two distances of different object using Friend Function in C++ 7. Write a Program for Addition and Subtraction of Two Polynomial Object using Operator Overloading in C++ 8. Write a C++ program to Implement Matrix Class using Constructor, Destructor, Copy Constructor, Overloading assignment operator. 9. Write a C++ program to implement complex number class with operator overloading and type conversions such as integer to complex, double to complex, complex to double. 10. Implement complex number class with necessary operator overloading and type conversions such as integer to complex, double to complex, complex to double etc. Implement Matrix class with dynamic memory allocation and necessary methods. Give proper constructor, destructor, copy constructor, and overloading of assignment operator. Overload the new and delete operators to provide custom dynamic allocation of memory. 11. Write a C++ program to Overload the new and delete operators for addition of vector elements to provide custom dynamic allocation of memory. 12. Write a Program for String concatenation using Operator Overloading concept in C++ 13. Write a Program for Implementation of Arithmetic Operations on Complex numbers using Constructor Overloading in C++. 14. Write a Program for String concatenation using Dynamic Memory Allocation in C++ 15. Write a C++ program to implement the template of linked list class 16. Write a C++ program to implement the Templates of standard sorting algorithms such as bubble sort, insertion sort, merge sort, and quick sort. 17. Write a Program for Implementation of Virtual Base Class in C++.

~ 73 ~

18. Define Point class and an Arc class. Define a Graph class which represents graph as a collection of Point objects and Arc objects. Write a method to find a minimum cost spanning tree in a graph. 19. Develop with suitable hierarchy, classes for Point, Shape, Rectangle, Square, Circle, Ellipse, Triangle, Polygon, etc. Design a simple test application to demonstrate dynamic polymorphism and RTTI. 20. Develop a template of linked-list class and its methods. 21. Design stack and queue classes with necessary exception handling. 22. Write a C++ program that randomly generates complex numbers (use previously designed Complex class) and writes them two per line in a file along with an operator (+, -, *, or /). The numbers are written to file in the format (a + ib). Write another program to read one line at a time from this file, perform the corresponding operation on the two complex numbers read, and write the result to another file (one per line). 23. Write a C++ program to implement the Queue class with necessary exception handling. 24. Write a Program for Student Grade Calculations in C++. 25. Write a Program for Employee Details in C++. 26. Write a Program for Convert Fahrenheit to Celsius in C++. 27. Write a Program for Implementation of Addition Operation of Octal Object in C++ 28. Write a Program for Managing Bank Account using Inheritance concept in C++. 29. Write a Program for Area of different dimensions using Virtual Function in C++. 30. Write a Program for Implementation of Pure Virtual Function in C++.

Java:
31. Write a Program for Area of Different Dimension Using Interface in Java 32. Write a Program for Student Mark Details using Interface in Java. 33. Write a Program for Developing Packages in Java 34. Write a Program for Arithmetic operations in Java 35. Write a Program to Implement Exceptions in Java. 36. Write a Program for Largest of two numbers in Java 37. Write a Program for Addition of two numbers using Data Input Stream in Java. 38. Write a Program for Program to Implement Exceptions in Java. 39. Write a Program for Odd or Even using Data Input Stream in Java 40. Write a Program for Factorial using Data Input Stream in Java.

~ 74 ~

~ 75 ~

~ 76 ~

~ 77 ~

~ 78 ~

~ 79 ~

~ 80 ~

Anda mungkin juga menyukai