I've gotten to a point with this sketch that it finally works, but only the first time through. The second time through it will return an incorrect answer, and subsequently it will return the same incorrect answer over and over no matter what I enter.
So I know the math and the defined functions are working. I'm guessing I need to 'reset' my variables but I don't know how - I have Googled this just like the last 300 odd problems I've had to solve but at last, I am defeated.
I have tried to "force" a reset with some of the variables, for example "final -= final;" at the end of the loop and also at the start but this didn't affect the results.
To answer your general question, yes, you have to set your variables to start values as they are global variables and are not put back to initial values when loop() repeats. You could write a function to do this and call it when needed.
It's basically good practice. A variable local to a function can not be changed in another function preventing coding mistakes.
int val1;
int val2;
void loop()
{
printVal1();
doSomethingWithVal2()
}
void printVal1()
{
Serial.println(val1);
}
void doSomethingWithVal2()
{
// do something that is not supposed to touch val1
// due to a typo, you use val1 instead of val2
val1++;
}
This results in a, possibly, difficult to find bug in your code. In this case it's probably easy to spot but if your code is more complex it becomes another story.
It can also be more memory efficient; variables declared inside a function cease to exist when the function is finished.
void loop()
{
func1();
func2();
}
void func1()
{
int i = 0;
...
...
}
void func1()
{
int j = 0;
...
...
}
If 'i' and 'j' were global variables, you would always have 4 bytes allocated for them. In the above, when func1 is called, 2 bytes are allocated for 'i'; once func1 finishes, those 2 bytes go out of scope (no longer exist). When you now call func2 (as shown in loop()), those 2 bytes can be used for the variable 'j'. You saved 2 bytes.
Note that those variables 'i' and 'j' in the above are not counted in the memory usage that the IDE reports which gives a 'false' representation of the amount of memory used while the code is running. You can change e.g. 'int i' to an array of 800 integers. You will get a low memory warning if it was a global variable; not so if it's a local variable inside func1(). This again can result in difficult to trace issues.
Conclusion:
it's a fine balance. Know what you're doing and there will not be problems