In: Computer Science
C++ please
#include <iostream> using namespace std; /** * defining class circle */ class Circle { //defining public variables public: double pi; double radius; public: //default constructor to initialise variables Circle(){ pi = 3.14159; radius = 0; } Circle(double r){ pi = 3.14159; radius = r; } // defining getter and setters void setRadius(double r){ radius = r; } double getRadius(){ return radius; } // method to get Area double getArea(){ return pi*radius*radius; } }; //main method int main() { //declaring and taking input of radius double r; cout<<"Enter radius: "; cin>>r; //making an object of class circle Circle c(r); //printing area of circle cout<<"Area = "<<c.getArea()<<endl; }
Write a for loop that displays the radius and area of the circles represented by the array you defined in the source code above.
//----------- Circle.cpp -----------
#include <iostream>
#include<limits>
using namespace std;
/**
* defining class circle
*/
class Circle
{
//defining public variables
public:
double pi;
double radius;
public:
//default constructor to initialise variables
Circle(){
pi = 3.14159;
radius = 0;
}
Circle(double r){
pi = 3.14159;
radius = r;
}
// defining getter and setters
void setRadius(double r){
radius = r;
}
double getRadius(){
return radius;
}
// method to get Area
double getArea(){
return pi*radius*radius;
}
};
//function that checks if cin is failed or not
//fail means invalid type is inputted for a variable.
//like giving string instead of number .
bool isInvalidInput()
{
//if cin is fail
if(cin.fail())
{
//clear the buffer.
cin.clear();
//ignore the characters.it need
limits header.
cin.ignore(numeric_limits<streamsize>::max(),'\n');
return true;
}
//if not return false.
return false;
}
//main method
int main()
{
//get number of circles to be created from user as
input.
int n;
cout<<"Enter Number of circles want to create:
";
cin >> n;
//if invalid input like entering string for n or n is
<= 0;
//print error msg and exit
if(isInvalidInput() || n <= 0 )
{
cout<<"Invalid number of
circles entered\n";
exit(1);
}
//array of circle.
Circle circles[n];
//radius
double r;
//get n number of circles from user.
for(int i =0;i<n;i++)
{
cout<<"\nEnter radius:
";
//get raidus
cin>>r;
//check for invalid input, if
invalid set radisu to 1
if(isInvalidInput())
{
cout<<"Invalid radius entered,setting radius to
1."<<endl;
r = 1;
}
//create a neew circle object for
the given radius.
Circle circle(r);
//insert in circles array
circles[i] = circle;
}
//print the radius and the area of the circle in
circles array.
for(int i =0;i<n;i++)
{
cout<<"\nRadius:
"<<circles[i].getRadius()<<" , Area:
"<<circles[i].getArea()<<endl;
}
return 0;
}
//------------- SAMPLE OUTPUT -----------
//please like the answer.