WAP to find area and circumference of a circle using call by reference
Objective
Write a C++ program to calculate the area and circumference of a circle using Call by Reference.
Algorithm / Approach
- Define a
class Circlewith functionsarea(int &r)andcircum(int &r). - Notice the ampersand (
&) in the parameter list. - In
main(), read the radiusa. - Pass
adirectly into the functions:c.area(a). - Calculate and print the math inside the functions.
main.cpp
#include<iostream>
using namespace std;
class Circle {
public:
void area(int &r) {
double ar = 3.14*r*r;
cout<<"Area = "<< ar<< endl;
}
void circum(int &r) {
double cir = 2*3.14*r;
cout<<"Circumference = "<< cir;
cout<< endl;
}
};
int main() {
int a;
cout<<"Enter Radius ";
cin>>a;
Circle c;
c.area(a);
c.circum(a);
return 0;
}
Expected Output
Enter Radius 7 Area = 153.86 Circumference = 43.96
Explanation of the Program
- Call by Reference means passing the actual original variable into a function, rather than a copy of it.
- By placing an
&before the parameter name (int &r), C++ creates an "alias" for the original variable passed in. Any changes made torinside the function would immediately affect the original variableainmain().
Complexity
Time Complexity
O(1)
Space Complexity
O(1)