Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to find area and circumference of a circle using call by reference

C++ Code Example — Miscellaneous Programs

ADVERTISEMENT

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

  1. Define a class Circle with functions area(int &r) and circum(int &r).
  2. Notice the ampersand (&) in the parameter list.
  3. In main(), read the radius a.
  4. Pass a directly into the functions: c.area(a).
  5. 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 to r inside the function would immediately affect the original variable a in main().

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT