The functions allow a programmer to divide a specific code into various sections, and each section performs a particular task. The functions are created to perform a task multiple times in a program.
The function is a type of procedure that returns the area of code from which it is called.
For example, to repeat a task multiple times in code, we can use the same set of statements every time the task is performed.
Advantages of using Functions
Let's discuss some advantages of using functions in programming, which are listed below:
The Arduino has two common functions setup() and loop(), which are called automatically in the background. The code to be executed is written inside the curly braces within these functions.
void setup() - It includes the initial part of the code, which is executed only once. It is called as the preparation block.
void loop() - It includes the statements, which are executed repeatedly. It is called the execution block.
But sometimes, we need to write our own functions.
Let's start writing the functions.
The method to declare a function is listed below:
We need a return type for a function. For example, we can store the return value of a function in a variable.
We can use any data type as a return type, such as float, char, etc.
It consists of a name specified to the function. It represents the real body of the function.
It includes the parameters passed to the function. The parameters are defined as the special variables, which are used to pass data to a function.
The function must be followed by parentheses ( ) and the semicolon ;
The actual data passed to the function is termed as an argument.
Let's understand with some examples.
Consider the below image:
Example 2: Here, we will add two numbers.
Consider the below code:
Similarly, we can perform arithmetic operations using the above concept.
Here, we will create a function that determines if a number is even or odd.
Consider the below code.
The output is shown below:
and so on...
Next TopicArduino Data Types