Imagine you need to write a program which reads birth day from a user & print his age. You may write something like this:
Suppose now you need to read another user birth day & print his age.
You may write something like this:
And later you found something wrong with blah blah code section. So you will correct it. Since you have used same code twice, you will need to fix that error twice. If you have used ten times that code, you’ll have to fix that error ten times. That is so much waste of time. That’s why we have functions.
Functions/Procedures allow us to use same calculation for different values.
So, if we have used blah blah code section within a function, we don’t need to fix the same code multiple times.
When we declare a function, first we need to specify the return type. Return type specifies the type of output value of that function. For example: If we return a number, return type is int.
Then we need to specify the name of that function. After that we specify parameter/argument list of that function. Each parameter is separated by a comma.
Here is an example:
This is how we use that function within our program:
As you can see, Instead of using blah blah code again & again, we call CalculateAge function. This simplifies our code & improves reusability. Also other programmers can use that function without thinking about its implementation (blah blah code section). So, they can focus on their own coding problems instead of thinking about blah blah code section.
(Also you can declare variables inside of the function. We called them as local variables.)