Functions
Learn about the basic way of code reuse.
Definition
The concept of functions in programming is similar to that in Mathematics. It's map that takes some parameters and return some result.
Functions help programmers give names for their code, making it easier to understand and analyze. They also help in abstracting things and reusing the code.
Syntax
Defining a Function
The syntax of defining a function goes as the following:
- The keyword
دالة
- The name of the function
- An opening bracket
(
- Arbitrary number of parameters, seperated by commas (each parameter consists of a type followed by a name)
- A closing bracket
)
- A colon
:
- The type of the returned value of the function (In case the function does not return a value the keyword
لاشيء
which means void or nothing should be used) - An opening brace
{
- Some code
- A closing brace
}
Example
The following example defines a function that takes two numbers as parameters, and then returns their sum.
دالة جامعة (رقم أ، رقم ب): رقم {
أرجع أ + ب؛
}
Calling a Function
Once we call on a function, it gets executed.
And the syntax for that goes as the following:
- The name of the function
- An opening bracket
(
- The values we want to pass as parameters (Their number should be equal to the number of parameters the function takes, which is defined in the function definition).
- A closing bracket
)
- A semicolon
؛
Example
Let's print the sum of every two consecutive numbers from 0 to 9 using the function we declared above.
كرر (متغير رقم س = 0؛ س < 10؛ س++) {
أكتب(جامعة(س، س + 1))؛
}