Function is a code block that executes certain task.
A void function doesn't return any value.
Example:
Output:
Via the return keyword a result can be returned.
Let's have an example in which rectangle's area is calculated by passing arguments about it's sides.
Example:
Output:
There are couple of things to mark:
lines 13 - 16
. It accepts two arguments -
widthArg
and heightArg
both of type double
.calcRectangleArea
returns a double
result.calcRectangleArea
is called at line 9
.area
.If a function returns value different than the specified type, it causes an exception.
In this case 5
should be replaced with string value.
Atline 12
the function expects argument of type int
.
At line 9
an argument of string type is passed.
The passed argument at line 9
should be replaced with integer value.
The function calcTrapezoidArea
expects 3 arguments but only 2 are passed to it.
Default value may be specified for function parameters.
Let's look at the following:
Output:
At line 10
the function argument is not passed thus it
takes the default value - 3
specified at line 13
.