oops lab 2007 man

31
OBJECT ORIENTED PROGRAMMING LAB MANUAL

Upload: mala-aarthy

Post on 25-Oct-2015

22 views

Category:

Documents


1 download

DESCRIPTION

ooop

TRANSCRIPT

Page 1: Oops Lab 2007 Man

OBJECT ORIENTED PROGRAMMING

LAB MANUAL

Page 2: Oops Lab 2007 Man

R.M.K. ENGINEERING COLLEGER.S.M. NAGAR, KAVARAIPETTAI –601 206

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Object Oriented Programming Laboratory(CS1205)

LAB MANUAL(Third Semester)

ANNA UNIVERSITY (2004 Regulation)

Page 3: Oops Lab 2007 Man

Syllabus

CS1205 OBJECT ORIENTED PROGRAMMING LAB EXPERIMENTS 0 0 3 100

C++

1. Programs Using Functions- Functions with default arguments- Implementation of Call by Value, Call by Address and Call by Reference

2. Simple Classes for understanding objects, member functions and Constructors- Classes with primitive data members- Classes with arrays as data members- Classes with pointers as data members – String Class- Classes with constant data members- Classes with static member functions

3. Compile time Polymorphism - Operator Overloading including Unary and Binary Operators.- Function Overloading

4. Runtime Polymorphism - Inheritance- Virtual functions- Virtual Base Classes- Templates

5. File Handling- Sequential access- Random access

JAVA

6. Simple Java applications - for understanding reference to an instance of a class (object), methods- Handling Strings in Java

7. Simple Package creation.- Developing user defined packages in Java

8. Interfaces- Developing user-defined interfaces and implementation- Use of predefined interfaces

9. Threading- Creation of thread in Java applications- Multithreading

10. Exception Handling Mechanism in Java- Handling pre-defined exceptions- Handling user-defined exceptions

Page 4: Oops Lab 2007 Man

LIST OF EXPERIMENTS:

CYCLE I

1.a. Write a C++ program to convert Fahrenheit to centigrade temperature.

b. Write a C++ program to find the sum of the digits of a given number.

c. Write a C++ program to perform matrix addition.

d. Write a C++ program to find the factorial of a given number using functions.

2.Write a program to simulate the operations of a stack.

3. Write a program to negate a complex numbers.

4. Write a C++ program to find square and cube of the given number using inline functions.

5. Write the C++ program to perform matrix transpose using constructor and destructor.

6. Write a program in C++ to perform addition to two complex numbers using the concept of friend function.

7. Write a program to increment the variables val1, val2 by overloading the ++operator.

8. Write a program to overload the +, -, * operator to add, to subtract and to multiply two matrices using friend function.

9. Write a program to overload the +operator to add two strings.

10. Write a function max to find the maximum value using function overloading.

maximum of 2 numbers among floats and among ints.

11.Write a program in C++ to perform Employee Information system using the concept of Single Inheritance.

12. Write a program in C++ to perform Banking Information System using the concept of Multiple Inheritance.

13. Write a program in C++ to perform Student Information System using the concept of

Multilevel Inheritance.

14. Write a C++ program which models the class hierarchy for book shop and processes objects of these classes using

pointers to the base class.

15. Write a program to find the string or number having maximum length using templates.

16. Write a program to perform Bubble sort for any type of data.

17.Write a C++ program to illustrate file Handling.

CYCLE II

JAVA Programs

1.Write a C++ program to display the pattern.

2.Write a program to find grade calculation using nested if statement

3.Write a program to perform arithmetic operations

4.Write a Program to check whether the given number is even or odd

5.Write a program to generate odd series

6.Write a program for average calculation using inheritance 7.Write a program to find the minimum of the three numbers8.Write a program to implement multiplication table generation

Staff in charge HOD Principal

Page 5: Oops Lab 2007 Man

INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

The history of OOP dates back to 1960 when research started through simula programming language.But the real credit goes to smalltalk- the first successful and complete object oriented language developed at Xerox Corporation’s PARC which took nearly 10 years to complete.In 1979,Bjarne Stroustrup from Bell labs started working on C++ language. The initial version was called “C with classes”.Later the name C++ was suggested. Since then,this language was refined until it became a language with its own personality.Like C,this language also has features of Portability,Brevity,Modular compatibility and speed.

C++ is an expanded version of C. In C, once a program exceeds from 25,000 lines of code, it becomes so complex that it is difficult to group it in a totality. The purpose of C++ is to allow the programmer to comprehend and manage larger, more complex programs.

Object Oriented Programming is a new way of approaching the job of programming. Object Oriented Programming has taken the best ideas of structured programming and combined them with several powerful concepts that encourage approaching the task of programming in a new way.

The concepts to be noted in any Object Oriented Programming are objects and classes. Object Oriented Programming uses objects and not algorithms as its fundamental building blocks. Each object is an instance of some class. Classes allow the mechanism of data abstraction for creating new data.

All Object Oriented Programming have the following traits in common.(a) Date Abstraction : The data abstraction is defined as a collection of datas and functions.

(b) Data Hiding: The class construct allows declaring data and member functions to be declared, as a Public and Protected group. The implementation details of a class can be hidden. This is done by data hiding principle.

(c) Data Encapsulation: The wrapping up of data and functions into a single unit (called Class) is known as encapsulation. The data is not accessible to the outside world and only those functions, which are wrapped in the class, can access it.

(d) Inheritance: Inheritance is the process by which objects of one class acquire the properties of objects of another class. The concept of inheritance provides the idea of reusability i.e. we can add additional features to an existing class without modifying it. OOP allows a programmer to build a hierarchy of classes.

(e) Polymorphism : Polymorphism means the ability to take more than one form. For eg, the data and operations may exhibit different behavior in different instances. The behavior depends upon the types of data used in the operation.

OBJECTS:In OOPs, data and behaviour are conceived of as classes whose instances are objects. An object as a self

contained entity that stores its own data and owns its own functions.An object can be a person, a place, or a thing with which the computer must deal. Some objects may correspond to real world entities such as students, employees, bank accounts, inventory items etc.

Objects mainly serve the following purposes:1.Understanding of the real world and a practical base for designers.2.Decomposition of a problem into objects depends on judgments and nature of the problem.Every object will have the data structures called attributes and behaviour called operations. In context of C++, the

term object (variable) refers to an instance of a class (data type).Thus the class defines the behaviour of possibly many objects(instances).Objects are also called reference variables, which are aliases for an object. Like ‘struct’ is a user defined data type in C,Class is a user defined data type in C++.A class defines the characteristics of its instances in terms of members: data members(state) and member functions(methods of operations).They also state their scope(visibility)of these members to other classes.Thus,the class defines the form of all objects that belong to that class.EXAMPLES OF OBJECTS:

Car, boy, girl, clock, book, tree, triangle.1.Person objects:Person classAttributes: name, age, sexOperations: speak (), listen( ),walk()2.Vehicle objects:Vehicle class

Page 6: Oops Lab 2007 Man

Attributes: name, model, and colorOperations: start(), stop(),accelerate( )3.polygon objects:Polygon classAttributes: vertices, border, color, fillcolor

Operations: draw( ),erase( ),move( )

SIMPLE C++ PROGRAMS:

EXERCISE 1.A:

Aim :To write a C++ program to convert Fahrenheit to centigrade temperature.

Algorithm:1.Input the Fahrenheit value.2.Calculate centigrade using the formula c=5.0/9.0*(Fahrenheit – 32).3.Print the result.4.End.

Out put:

EXERCISE 1.B:

Aim :To write a C++ program to find the sum of the digits of a given number.

Algorithm:1.Input the number.2.Extract the digit one by one from the given number and find the sum of the digits repeatedly until the number becomes zero.3.Print the result.4.End.

Out put:

EXERCISE 1.C:Aim :

To write a C++ program to perform matrix addition.Algorithm:

1.Input the matrix A and matrix B.2.Perform the matrix addition.3.Print the resultant matrix.4.End.

Out put:

Exercise 1.d:Aim :

To write a C++ program to find the factorial of a given number using functions.Algorithm:

1.Input the number.2.Pass the number as an argument to the function fact().3.Find the factorial of the given number and return the value to the main .4.Print the result.5.End.

Out put:

Sample C++ ProgramAim:

To write a program in C++ to read the Name and Basic Salary and print the same.#include <iostream.h>using namespace std;class emp{

private:

Page 7: Oops Lab 2007 Man

char name [20];int basicpay;

public:void getdetail();void printdetail();

};void emp::getdetail(){

cout<<”Enter name:”; cin>>getline(name,20);

cout<<”\n Enter Basic Pay:”; cin>>basicpay;}void emp::printdetail(){

cout<<”Name :”<<name<<”\n”;cout<<”Basic pay :”<<basicpay;

}int main(){

emp empinfo;empinfo.getdetail();empinfo.printdetail();return 0;

}

EXERCISE 2:Aim : To write a program to simulate the operations of a stack.Algorithm :

1. Declare an array & a variable top.2.Initialise top to 03.For push operation perform the following steps:

a) Assign the element to the location pointed by top.b) Increment top

4.For pop operation perform the following stepsa) Read the element pointed by topb) Decrement top

5.End.Out put:

EXERCISE 3:Aim :

To write a program to negate a complex numbers.Algorithm:

1.Declare the real and imaginary part of a complex number.2.Read the real & imaginary part of the complex number by writing a function read( ).3.Perform the negation on the complex number by creating a function negate().4.Print the resultant complex number by creating a function display ( ).5.End.

Out put:

INLINE FUNCTIONS:Functions execution involves the overhead of jumping to and from the calling statement. Trading of this

overhead in execution time is considerably large. whenever a function is small,and hence in such cases,inline functions can be used.A function in C++ can be treated as a macro if the keyword inline precedes its definition.The syntax of representing the inline function is shown in below:

Inline returntype function_name(parameters){

// body of the main function

Page 8: Oops Lab 2007 Man

}

EXERCISE 4:Aim :

To write a C++ program to find square and cube of the given number using inline functions.Algorithm:

1.Get the number.2.Calculate square and cube of the given number using inline function.3.Display the result.4.End.

Out put:

CONSTRUCTOR:Normally, when we create a new object garbage values is stored in variables initially and accessing this values

before initializing will produce some unwanted result. To avoid this situation C++ has a function called “Constructor” which will be called along with the object declaration. Now, let us see an example program, which will print garbage values when the variables are not get initialized.

DECLARATION OF A CONSTRUCTOR

class class_name ( ){public:class_name( ); //with out parameterclass_name (argument1, argument2); // with parameter};

SYNTAX FOR DEFINING A CONSTRUCTOR

Class_name :: Class_name( ){

} DESTRUCTOR

Like constructor, this is another special function present in a class. The action of this function is just reverse of the constructor in the sense that it is called when an object ceases to exist, i.e. when an object is out of scope it is automatically called. While defining a destructor for a class the following points should be kept in mind.

1.Like constructor, the destructor function also has the same name as the class but proceeded by a tilde (~). 2.The destructor has no arguments and also does not return any value. And one more difference between constructor and destructor is, while a class can have multiple constructors, it can have only one destructor.

DECLARATION OF A DESTRUCTOR

Class Class_name ( ){public:

~ class_name( ); //without parameter

};SYNTAX FOR DEFINING A DESTRUCTOR

Class_name ::~ Class_name( ){ }

EXERCISE 5:Aim :

To write the C++ program to perform matrix transpose using constructor and desturctor.

Page 9: Oops Lab 2007 Man

Algorithm:1.Create a class called matrix.2.Initialize a matrix-using constructor and include the explicit destructor.3.Perform matrix transpose i.e. change the rows into columns and columns into rows for the given matrix using the member function transpose ()4.End

Out put:

FRIEND FUNCTIONS :

The main concepts of the object oriented program paradigm are data hiding and data encapsulation,Non member functions cannot access private data.This rule has broken by the concept of friend functions.The scope of a friend function is not limited to the class in which it has been declared as a friend.

SYNTAX:Class class_name{public: friend data_type function_name(arguments if any);};//defining the friend function outside the class

EXERCISE 6:Aim :

To write a program in C++ to perform addition to two complex numbers using the concept of friend function. Algorithm:

1.Create a class called complex.2.Get the complex numbers using getcomplex().3.Perform the add operation using the friend function addcomplex().4.Display the result using outcomplex().5.End.

Out put:

POLYMORPHISM

Polymorphism means more than one form. In OOP, Polymorphism refers to identically named methods that have different behaviour depending on the type of object they refer.

For eg., an operation may exhibit different behaviour in different instances. The behaviour depends upon the types of data used in the operation.

The concept of polymorphism can be implemented using the overloaded functions and operators. The overloaded member functions are selected for invoking by matching arguments. The compiler knows this information at the compile time. This is called static binding. Also known as compile time Polymorphism.

Polymorphism

Compile time Runtime

FunctionOverloading

OperatorOverloading Virtual function

Class A{

int X;Public:

Void show ();};

Class B: public{

int Y;Public:

Void show ();};

Page 10: Oops Lab 2007 Man

Since the prototype of show () is same in both derived and base class, the function is not overloaded and therefore static binding does not apply. This is known as run time Polymorphism. This is achieved by using a mechanism known as virtual function.

OPERATOR OVERLOADING:

Operator overloading is an important technique that has enhanced the power of extensibility of C++.C++ tries to make the user defined data types behave in much the same way as built in same syntax that is applied

to basic type.

We can overload all C++ operators except 1.class member access operator (.* )2.scope resolution operator(::)3.size of operator (size of)4.conditional operator(?:)

DEFINITION:Operator overloading is a technique used to change the predefined operation of an operator for existing data types

to a new operator for user defined data types.

SYNTAX:1.Defining inside the class:

return type operator symbol(argument list){

}

2.Defining outside the class:return type class_name::operator symbol(argument list){

}3.a.Overloading unary operator:

return type operator unary_operator_symbol(){

}Calling the function:

Object2=Object1 unary_operator_symbol 3.b.Overloading binary operator:

return type operator binary_operator_symbol(operand_2){

}Calling the function:

Object3=object1 binary_operator_symbol object23.c.Overloading binary operators with friend functions:

FRIEND FUNCTION DECLARATION:Class class_name{friend return type operator symbol(operand1,operand2);};

FRIEND FUNCTION DEFINITION:Return type operator symbol(operand1,operand2){}

EXERCISE 7:Aim :

Page 11: Oops Lab 2007 Man

To write a program to increment the variables val1, val2 by overloading the ++operator.Algorithm:

1.Create a class called unary.2.Initialize val1=0 and val2=0 using constructor.3.To increment val1 and val2 overload the unary operator ++.4.Display the result using showdata ().5.End.

Out put:

EXERCISE 8:Aim :

To write a program to overload the +, -, * operator to add, to subtract and to multiply two matrices using friend function.Algorithm:

1.Create a class called matrix.2.Get the matrices using matrixinput().3.Overload the binary operators +, -, * to perform matrix addition,subtraction,multiplication using friend function.4.Display the output using matrixprint().5.End.

Out put:

EXERCISE 9:Aim :

To write a program to overload the +operator to add two strings.Algorithm:

1.Create a class called string.2.Initialize the string using constructor.3.Get the two strings using getstring().4.Overload the operator + to concatenate two strings.5.Display the result using showstring()6.End.

Out put:

FUNCTION OVERLOADING:If two or more functions are defined with the same name but differs by number and type of its arguments,then the

functions are said to be overloaded

SAMPLE EXAMPLE:Aim:

Write a program to find the absolute value for real ,int,long int datatypes using Function overloading.

#include<iostream.h>int abs(int i){

cout<<”using integer abs( )”;if(i<0)return(-i);elsereturn( i);

}double abs(double d){cout<<”using integer abs( )”;return d<0.0 ? –d:d;}

long abs(long l){cout<<”using integer abs( )”;return l<0.0 ? –l:l;}int main()

Page 12: Oops Lab 2007 Man

{cout<<abs(-10);cout<<abs(-11.0);cout<<abs(-9L);return 0;}

EXERCISE 10:Aim :

To write a function max to find the maximum value using function overloading.maximum of 2 numbers among floats and among ints.

Algorithm:1.Create a class called maximum.2.Input the values.3.Use Function overloading.4. Find the maximum number among 2 ints and among 2 floats separately using the function max2().5.Display the results.6.End.

Out put:

INHERITANCE

Inheritance is the process of creating new classes called as derived class from an existing class called as base class. The derived class inherits all capabilities of the base class. It can also add some more features to this class. The base class remains unchanged. The main advantages are reusability of code, increasing the reliability of code.

First inheriting all the variables and behaviour defined by some private class and then adding specified variables and behaviour of the new class create classes.

A number of terms are used to describe classes that are related through inheritance. A base class is often called the ancestor, parent or superclass, and a derived class is called the descendent, child or subclass. A derived class may itself be a base class from which additional classes are derived. There is no specific limit on the number of classes that may be derived from one another.

Inheritance is classified into the following forms based on the levels of inheritance and interrelations among the classes involved in the inheritance process.

Single Inheritance Multiple Inheritance Multilevel Inheritance

DEFINING DERIVED CLASSES:

Class derived_class_name: mode base_class_name{new member variable declaration-------------new member function declaration and definition-------------};

SINGLE INHERITANCE

Derivation of a class from only one base class is called single inheritance.

EXAMPLE:

A

B

Page 13: Oops Lab 2007 Man

Class A{

int a,b;public:

void getdata();void putdata();

};Class B: public A{

int c;public:

void getdata();void putdata();

};

EXERCISE 11:Aim :

To write a program in C++ to perform Employee Information system using the concept of Single Inheritance.Algorithm:

1.Create a class called employee.Data members:empno,empname,basicpay.Member functions:getinfo(),printinfo().

2.Derive the class called worker.Data members:da,hra,pf,netpay.Members functions:getpaydetails(),print paydetails().

3.Get and display the details by calling the appropriate member functions.4.End.

Out put:

MULTIPLE INHERITANCE

Derivation of a class from several (two or more) base classes is called multiple inheritance.

SYNTAX:Class A{ int a,b;public : void getdata();

void putdata();};Class B{ int x,y;public : void getdata(); void putdata();};

Class C: public A, B{ int d;public : void getdata();

void putdata();};

A B

C

Page 14: Oops Lab 2007 Man

EXERCISE 12:Aim :

To write a program in C++ to perform Banking Information System using the concept of Multiple Inheritance.Algorithm:

1.Create a class called Account.Data members: Customer_name, Accountnumber.Member functions: getdetails (), showdetails ().

2.Create a class called balance.Data members: balance, interest_rateMember functions: getbalance (), showbalance (), cal_compound ().

3.Derive the class called bank.Data members: amount, current_balance.Member functions: deposit (), withdrawal (), compound_interest ().

4.Simulate the banking operations by calling appropriate member functions.5.End.

Out put:

MULTILEVEL INHERITANCE

Derivation of a class from another class, which is already a derived class, is called multiple Inheritance.

SYNTAX :

Class A{ int a,b;public : void getdata();

void putdata();};Class B : public A{ int x,y;public : void getdata();

void putdata();};

Class C: public B{ int d;public : void getdata();

void putdata();};

EXERCISE 13:Aim :

To write a program in C++ to perform Student Information System using the concept of

A

B

C

Page 15: Oops Lab 2007 Man

Multilevel Inheritance.Algorithm:

1.Create a class called studinfo.Data members:studname,rollno.Member functions:getstudinfo(),printstudinfo().

2.Derive a class called marksinfo.Datamembers:lang1,lang2,sub1,sub2,sub3.Member functions:getmarks(),printmarks().

3.Derive a class called result from marksinfo.Data members :total,grade.Member functions:print_total_grade().

4.Display the result for a particular student by calling appropriate member functions.5.End.

Out put:

VIRTUAL FUNCTIONSWhen we use the same function name in both the base & derived classes, the function in base class is

declared as virtual using keyword virtual preceding its normal declaration. When a function is made virtual, C++ determines which function to use at runtime based on the type of object pointed to the base pointer, rather than the type of the pointer.

EXAMPLE#include<iostream.h>#include <string.h>class Father{

Char name [2];Public:

Father (char *fname){strcpy(name,fname);}

virtual void show(){cout <<”Father name”<<name <<endl;}

};class son:public Father{

char name[20];Public:

Son (char *Sname, char *fname):Father (fname){strcpy(name, sname);}

}

void show(){cout <<”Son name”<<name<<endl;}};void main(){

father *fp;father f1(“Eshwarappa”);

fp=&f1;fp show();son s1(“Raj Kumar”,”Eshwarappa”);fp=s1;fp show();

Page 16: Oops Lab 2007 Man

}

EXERCISE 14:Aim :

To write a C++ program which models the class hierarchy for book shop and processes objects of these classes using pointers to the base class.Algorithm:

1.Create a class called media.Data members:title,publication.Member functions:readdata(),showdata().

2.Create the derived classes called book and tape from media base class.Data member for book class:no_of_pages,price.Member functions:readdata(),showdata().

Data member for tape class:playing_time,price.Member functions: readdata (), showdata ().

3.Defined the member functions as virtual functions in the base class.4.Display the details of books and tapes,by calling appropriate member functions.5.End.

Out put:

TEMPLATESFUNCTION TEMPLATES AND CLASS TEMPLATES

The normal meaning of the word “template” accurately reflects its use in C++. A template allows the construction of a family of template functions and classes to perform the same operation on different data types. The templates declared for functions are called function templates and those declared for classes are called class templates. They perform appropriate operations depending on the data type of the parameters passed to them.

Templates support generic programming, which allows developing reusable software components such as functions, classes, etc., supporting different data types in a single framework. For, instance, functions such as sort, search, swap, and etc., which support various data types, can be developed.

THE GENERAL FORM OF A TEMPLATE FUNCTION DEFINITION IS :

template <class T type> returntype functionname(parameter list ){

}

EXAMPLE:

#include <iostream.h>template <class X> void swapargs (X &a, X &b){X temp;Temp=a;A=b;B=temp;}void main(){int I=10,j=20;double x=10.1,y=23.3;char a=’x’, b=’z’;cout<<”Original i, j:”<<I<<j;cout<<”Original x, y:”<<x<<y;cout<<”Original a, b:”<<a<<b;swapargs(i,j);swapargs(x,y);swapargs(a,b);cout<<”Swapped i, j”<<i<<’ ‘ <<j;cout<<”Swapped x, y”<<x<<’ ‘ <<y;cout<<”Swapped a, b”<<a<<’ ‘ <<b;

Page 17: Oops Lab 2007 Man

}

EXERCISE 15:Aim :

To write a program to find the string or number having maximum length using templates.Algorithm:

1.Create a template of type T that has max function.2.The function accepts the strings or numbers as parameters.3.Inside the template, compare the two elements.4.Display the result.5.End.

Out put:

EXERCISE 16:Aim :

To write a program to perform Bubble sort for any type of data.Algorithm:

1.Create a template of type that has bubble function.2.The function accepts T array (integer array or character array) and an integer(no of items to sort) as parameters.3.Inside the template, compare the two elements (characters or numbers) and perform the swapping if needed.4.Display the sorted elements.5.End.

Out put:

CLASS TEMPLATES:Similar to functions, classes can also be declared to operate on different data types. Such classes are called class

templates. A class template specifies how individual classes can be constructed similar to normal class specification. These classes model a generic class, which support similar operations for different data types.

THE GENERAL FORM OF A TEMPLATE FUNCTION DEFINITION IS :

template <class T1,class T2,….> class classname{//data items of template type T1, T2,….T1 data1;…//functions of template arguments T1, T2, …Void func1 (T1 &a, T2 &b);…T func2 (T2 *x,T2 *y);};

EXERCISE 17:Aim :

To write a C++ program to add two different data types in a class template.Algorithm:

1.Create a class template that accepts different data types T1,T2.2.Use the member function sumnumbers () to add the given datas inside the template.3.Display the result.4.End.

Out put:

FILE HANDLINGEXAMPLE:PROGRAM TO ILLUSTRATE FILE HANDLING

#include<iostream.h>#include<fstream.h>#include<iomanip.h>#include<stdlib.h>class student{

Page 18: Oops Lab 2007 Man

char name [20];int rollno;

public:void print(){cout<<”\nroll number”<<rollno;cout<<”\nName”<<name;}void store();void display();

};void student ::store(){ int n,i;

student s1;ofstream stud(“Student.dat”);cout<<”\nenter the number of record to create..”0;cin>>n;cout<<”enter the roll no and name one by one”;for(i=0;i<n;i++){cin>>s1.rollno>>s1.name;stud.write((char*)&s1,sizeof(s1));}stud.close();

}

void student ::display(){ student s1;

ifstream stud(“Student.dat”);while (stud)

{stud.read ((char*)&s1,sizeof(s1));s1.print():

}stud.close();

}void main(){ student s;

s.store();sssss.display();

}

JAVA PROGRAMS;

//TITLE : DISPLAY THE PATTERN

class display{public static void main(String args[]){for(int i=1;i<=5;i++){for(int j=1;j<=i;j++){System.out.print("\t"+i);}

Page 19: Oops Lab 2007 Man

System.out.println();}}}

//OUTPUT//1//1 2//1 2 3//1 2 3 4//1 2 3 4 5

//TITLE : GRADE CALCULATION USING NESTED IF STATEMENT

import java.*;public class grade{public static void main(String args[]){int a=98,b=99,c=90,d=98,e=86,f,g;f=a+b+c+d+e;g=f/5;System.out.println("Total="+f);System.out.println("Average="+g);if(g>90)System.out.println(" Grade :"+" o ");else if(g<90&&g>75)System.out.println(" Grade :"+" a ");else if(g<75&&g>50)System.out.println(" Grade : "+" b ");else if(g<60)System.out.println("Need to improve");}}

//OUTPUT//TOTAL :471//AVERAGE:94.2//GRADE:O

Page 20: Oops Lab 2007 Man

//TITLE : TO PERFORM ARITHMETIC OPERATIONS

import java.*;public class maths{public static void main(String args[])throws Exception{float a=10,b=20,c;char ch;System.out.println("a.addition b.subraction c.multiplication d.division ");ch=(char)System.in.read();switch (ch){case 'a':c=a+b;System.out.println("addition"+c);break;

case 'b':c=a-b;System.out.println("Subraction="+c);break;case 'c':c=a*b;System.out.println("Mulitiplication="+c);break;case 'd':c=a/b;System.out.println("division="+c);break;}}}//OUTPUT//a.addition b.subraction c.multiplication d.division //a//addition=30

//TITLE : EVEN OR ODD

public class number{public static void main(String args[]){int a=10;if(a%2==0){System.out.println("10 is even");

Page 21: Oops Lab 2007 Man

}elseSystem.out.println("10 is odd");}}//OUTPUT//10 IS EVEN

//TITLE : TO GENERATE ODD SERIES

public class odd{public static void main(String args[]){int n=31;System.out.println("The odd series is");for(int i=1;i<=n;i=i+2)System.out.println("\t"+i);}}

//OUTPUT//The odd series is://1 3 5 7 9 11 13 15 17 19 21 23 25 27 29

//TITLE : AVERAGE CALCULATION USING INHERITANCE

import java.*;class marks{float f;void mark(){int a=89,b=90,c=78,d=97,e=100;f=a+b+c+d+e;System.out.println("Total marks :"+ f );}}class average extends marks{void avg(){float t;t=f/5;System.out.println("Average:"+t);}}

Page 22: Oops Lab 2007 Man

public class report extends average{public static void main(String args[]){report r=new report();r.mark();r.avg();} }

//OUTPUT//TOTAL : 454//AVERAGE : 90.8

//TITLE : MINIMUM OF THE THREE NUMBERS

public class small{public static void main(String args[]){int a=10,b=20,c=30;if((a<b)&&(a<c)){System.out.println("10 is small");}else if((b<a)&&(b<c)){System.out.println("20 is small");}else{System.out.println("30 is small");}}}

//OUTPUT//10 IS SMALL

//TITLE : MULTIPLICATION TABLE GENERATION

public class table{public static void main(String args[]){

Page 23: Oops Lab 2007 Man

int a=5,i=1,b;while(i!=21){b=5*i;System.out.println("5*"+i+"="+b);i++;}}}

//OUTPUT//5*1=5//5*2=10//5*3=15//5*4=20//5*5=25//5*6=30//5*7=35//5*8=40//5*9=45//5*10=50//5*11=55//5*12=60//5*13=65//5*14=70//5*15=75//5*16=80//5*17=85//5*18=90//5*19=95//5*20=100

Page 24: Oops Lab 2007 Man