Area, circumference of circle using two functions – CSKC
Sign In

Search

Code Learning #CPP#2182    siteicon   siteicon  

Area, circumference of circle using two functions

Finding and area and circumference of a circle using two separate functions for each of them

Learning Objectives

  • Making multiple functions in a program.
  • Using global variables in two functions.
  • Using functions directly in the output chain without declaring an intermediate variable.
  • Use of mathematical expression directly in the return statement.

Source Code

TC++ #2182

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

  Related ( ? ) :

Code Understanding

double area(double); double circum(double);
These are protoypes of two functions where return types are double type data and input parameter is also double type data.

double const PI=3.1416;
This is global variable declaration above the main() routine. This is declared globally so that it can be used in multiple functions. It has been declared as const as the value of PI can not be modified at any other place.

double r; cout<<“Give radius of circle :” ; cin>>r;
These statements for collecting value of r.

cout<<“Area of circle = “<<area(r)<<endl;
Here the area(r) function is being called within the cout chain of output display. This kind of call first calculates the value by going to the function and then the returned value is displayed immediately. This type of call avoid a declaration of an intermediate variable to store the returned data.

cout<<“Circumference of circle = “<<circum(r)<<endl;
Another call for display of circumference is being given here using the function circum(r).

double area(double rad)
{
  return PI*rad*rad;
}
This is function definition of area. It returns the value of area by calculating the area within the return expression. Calculating simple mathematical expression within return statement also saves use of an intermediate variable.

double circum(double rad)
{
return 2*PI*rad;
}
This is function definition to calculate the circumference. Similar to above the calculation expression is given directly in the return statement.

Notes

  • Although as per theory multiple functions can also be defined above the main routine to avoid function prototype declaration statements, it is still advisable to declare function prototypes before the main routine and write the function definitions with the whole body below the main routine, the way it has been done in this example.

Common Errors

  • Mismatch in function prototype datatypes and function definition data types is the most common error students often do.


Suggested Filename(s): fn-area-circum.cpp



Share

Created: 5-Jan-2018 01:37 | Updated: 15-Sep-2018 14:06|