Why are functions useful?
How to define a function called myFunction?
int myFunction(int parameter1, float parameter2)
{
// write the function body in here
return intVal;
}
Where you can have as many or few parameters as you want and the return value has to be of the same type as the header.How to write a function that will add 2 numbers?
int add(int number1, int number2)
{
int answer;
answer = number1 + number2;
return answer;
}Can you show the newly defined add function being used?
int sum;
sum = add(4,7); // sum is set to 11
sum = add(5,6,7); // ERROR - needs 2 parameters.
How to define a function that will flash an LED?
void flash(int interval)
{
digitalWrite(LEDpin, HIGH);
delay(interval);
digitalWrite(LEDpin, LOW);
delay(interval);
return; // this line is optional because no return value
}Example usages of flash function?
flash(1000); // a slow 1 sec flash
flash(100); // much faster
flash(); // ERROR - need a parameter
What does void return type mean?
No return statement is required.
what can the for loop be used for?
repeating an action a number of times:
for (A; B; C)
{
// things to be repeated
}what are A B and C in the above question?
how does:
int x = 0;
for (int i=0; i
int i=0 - this initialises an integer variable called i to be 0.
i
how to work out factorial 5 using a for loop?
int x = 1;
for (int i=1; i
what does for(; ;) do?
creates an infinite loop
how to get out of an infinite loop?
use break keyword; very useful if combined with an if statement.
what is a better way of setting up a loop which stops when something happens?
the do.. while() loop does something(s) as long as a condition holds.
do
{ // things to repeat
}
while(condition)what are the numbers for false and true?
false - 0
true - 1