<< Chapter < Page | Chapter >> Page > |
If you did it all correctly, your program should calculate the square root. (For reasons that will become apparent later, I will refer to the code that you inserted as in-line code.)
Suppose that further on in your program you discover that you need to calculate the square root of another number. And later, you discover that youneed to calculate the square root of still another number. Obviously, with a few changes, you could copy your original code and insert it as in-line code at each location in your program where you need to calculate the square root ofa number.
However, after doing this a few times, you might start asking if there is a better way. The answer is "yes, there is a better way."
The better way is to create a separate program module that has the ability to calculate the square root and to make that module available for use as a helperto your main program each time your main program needs to calculate a square root. In some programming languages, this separate program module is oftencalled a function or a method. In scratch 2.0, it doesn't have a specific name. I will refer to it as a custom block . You create a custom block in Scratch 2.0 by selecting the More Blocks toolbox shown in Image A .
Most modern programming languages provide a large number of pre-written functions that are already available for your use.
In addition to the library functions that are already available, if you need a function to perform some operation and there is no library function alreadyavailable to perform that operation, you can write your own function.
A similar library for mathematical functions exists in Scratch 2.0. The library is accessed using the bottom block in the Operators toolbox with the selection sqrt shown in Image B .
Image C shows the different mathematical function selections that are available in the pull down list of the block. (Note that the fourth one from the top is the sqrt function.)
Normally, in the case of designing and writing a function such as one that can calculate the square root of a number, it is desirable to write it in such away that it can calculate the square root of any number (as opposed to only one specific number) . This is accomplished through the use of something called parameters.
The process of causing a function to be executed is commonly referred to as calling the function.
When your program calls the square-root function, it will need to tell the function the value of the number for which the square root is needed. Ingeneral, many functions will require that you provide certain kinds of information when you call them. The code in the function needs this informationto be able to accomplish its purpose.
Notification Switch
Would you like to follow the 'Teaching beginners to code' conversation and receive update notifications?