We have already encountered one function named main. It is special function called at the beginning of the program.
Use of function
Example : Suppose we want to write a program to compute the area of three triangles. We could write out the formula three times or we could create a functionto do the work.
Syntax:
// defining function
function_type function_name(parameters)
{
// statement(s)
}
// calling function
function_name(arguments);
- function_type is the data type of the data that function will return and if the written type is void then no data will be returned.
- function_name follows the same rules as variable name. This is not a coincidence, because both function and variable names are Identifier.
- parameters is a variable in a function definition. Parameters are optional.
- When a function is called, the arguments are the data passed into the function's parameters.
Example with parameters
#include<iostream>
using namespace std;
float triangle(float width,float height)
{
float area;
// area of triangle
area = width * height / 2.0;
return area;
}
int main()
{
cout<<"Triangle #1 : "<< triangle(1.3,4.7) <<endl;
cout<<"Triangle #2 : "<< triangle(4.1,2.1) <<endl;
cout<<"Triangle #3 : "<< triangle(6.7,4.3) <<endl;
return 0;
}
Output
Triangle #1 : 3.055 Triangle #2 : 4.305 Triangle #3 : 14.405
Example without parameter
#include <iostream>
using namespace std;
void area()
{
float area_circle;
float rad;
cout<<"\nEnter the radius : ";
cin>>rad;
area_circle = 3.14 * rad * rad ;
cout<<"\nArea of Circle = "<<area_circle;
}
int main()
{
area();
area();
return 0;
}
Output
Enter the radius : Area of Circle = 78.5 Enter the radius : Area of Circle = 113.04
0 Comments