Saturday 17 September 2011

Function overloading


Function overloading
Aim:
To write a C++ program to find the volume of cube, rectangle and cylinder using function overloading.
Algorithm:
Step 1: Create a class as shape.
Step 2: Declare the data members as a, l, b, h, and r.
Step 3: Declare the member function as volume with different arguments.
Step 4: Volume function calculates the volume of cube, cylinder and rectangle based on the parameter passed to it.
Step 5: In the main, create the object for the shape class.
Step 6: Call the function using objectname.functionname();
Program:
#include<iostream.h>
#include<conio.h>
class shape
 {
  int a,l,b,h;
  float r;
  public:
   void  volume(int);
   void volume(int,int,int);
   void volume(float,int);
  };
 void shape :: volume(int a)
  {
   cout<<"Volume of the cube is:"<<a*a*a;
  }
 void shape :: volume(int l,int b,int h)
  {
   cout<<"Volume of the rectangle is :"<<l*b*h;
  }
 void shape :: volume(float r,int h)
  {
   cout<<"Volume of the cylinder is:"<<0.33*3.14*r*r*h;
  }
 void main()
  {
   shape s;
   int a1,l1,b1,h1,h2;
   float r1;
   clrscr();
   cout<<"CUBE:"<<endl;
   cout<<"~~~~~~~~~~~~~~~~~~~~"<<endl;
   cout<<"Enter the value of a:";
   cin>>a1;
   s.volume(a1);
   cout<<endl<<endl<<"RECTANGLE:"<<endl;
   cout<<"~~~~~~~~~~~~~~~~~~~~"<<endl;
   cout<<"Enter the value of length, breadth and height:";
   cin>>l1>>b1>>h1;
   s.volume(l1,b1,h1);
   cout<<endl<<endl<<"CYLINDER"<<endl;
   cout<<"~~~~~~~~~~~~~~~~~~~~"<<endl;
   cout<<"Enter the radius and height:";
   cin>>r1>>h2;
   s.volume(r1,h2);
   getch(); }

Output:

CUBE:
~~~~~~~~~~~~~~~~~~~~
Enter the value of a:7
Volume of the cube is:343

RECTANGLE:
~~~~~~~~~~~~~~~~~~~~
Enter the value of length, breadth and height:6
4
5
Volume of the rectangle is :120

CYLINDER
~~~~~~~~~~~~~~~~~~~~
Enter the radius and height:5.4
3
Volume of the cylinder is:90.646779

0 comments:

Post a Comment