In: Computer Science
IN C++
Modify the above program to compute the side area, total area, and volume of a cylinder and the area and volume of a sphere, depending on the choice that the user makes. Your program should ask users to enter 1 to choose cylinder or 2 for sphere, and display an "invalid choice error" for other values.
For a cylinder, we want to compute:
Side area: (2*PI*r) * h
Total Area: 2*(PI*r2) + Side area
Volume: (PI*r2)*h
For a sphere, we want to compute:
Surface area: 4*PI*r2
Volume: (4.0/3.0)*PI*r3.
Use overloading whenever possible. Provide comments for any functions that are overloaded and explain why they could be overloaded
In this program, we are going to overload two function
The code for the program looks is attached below.
#include<bits/stdc++.h>
using namespace std;
#define Pi 2*acos(0.0)
//Overloading on volume for Sphere
long double volume(double r){
r = r*r*r;
return (4.0/3.0)*Pi*r;
}
//Overloading on voulme for Cylinder
long double volume(double r, double h){
return Pi*r*r*h;
}
// sideArea for Calculating the Side Area of Cylinder
long double sideArea(double r, double h){
return (2.0)*Pi*r*h;
}
// Overloadig on totalArea for Cylinder
long double totalArea(double r, double sideArea){
r = r*r;
return ((2.0)*Pi*r)+(sideArea);
}
// Overloading on totalArea for surface Area of Sphere
long double totalArea(double r){
return (4.0)*Pi*r*r;
}
int main(){
int x;
cin>>x;
if(x == 1){
cout<<"For cylinder enter the value of radius and height respectively\n";
long double rCy,hCy;
cin>>rCy>>hCy;
long double sideAreaCy, totalAreaCy, volumeCylinder;
sideAreaCy = sideArea(rCy, hCy); // No function Overloading is used
totalAreaCy = totalArea(rCy, sideAreaCy); // Using totalArea as Fucntion Overloading
volumeCylinder = volume(rCy, hCy); //volume of Cylinder ----> Function Overloading
cout<<"Side Area of Cylinder : "<<sideAreaCy<<endl; // Print the side Area of Cylinder
cout<<"Total Area of Cylinder : "<<totalAreaCy<<endl; // Print the total Area of Cylinder
cout<<"Volume of Cylinder : "<<volumeCylinder<<endl; //Print the volume of Cylinder
}else if( x == 2){
cout<<"For Sphere enter the value of radius \n";
long double rSp;
cin>>rSp;
long double surfaceArea, volumeSphere;
surfaceArea = totalArea(rSp); //Surface Area of Sphere Using totalArea Function -----> Function Overloading
volumeSphere = volume(rSp); //Volume of Sphere using voulme Function ---------> Function Overloading
cout<<"Surface Area of Sphere : "<<surfaceArea<<endl; //Print Surface Area of Sphere
cout<<"Volume of Sphere : "<<volumeSphere<<endl; // Print the Volume of Sphere
}else{
cout<<"invalid choice error\n";
}
return 0;
}
Output