We discussed variables and sub-functions previously here.
Now let's discuss how to use them in the NQC language (and most other textual programming languages like C,Java, Python)
Remember, a variable is a symbolic name for a memory cell.
With NQC, a programmer must declare a variable, then s/he can put values into the variable or get values out, e.g.,
task main ()
{int greens; // declare the variable 'greens' as an integer (whole number)
greens=0; // assigns the value 0 to the variable 'greens'
if (greens==0) // check the value of 'greens' and compare it to 0
{// ... do something
The declaration statement names some memory cell:
greens -----> 1000
| address | value |
| 1000: | |
| 1004: | |
| 1008: |
The assignment statement puts a value in that memory cell:
| address | value |
| 1000: | 0 |
| 1004: | |
| 1008: |
You must always declare a variable for assigning to it, and you should always assign to it before checking it.
Question 1: How would you add one to the previous value of 'greens'?
Question 2: How would you use a variable to do something n times?
Sub-Functions allow us to break a program into small, understandable parts, to give a name to a sequence of commands.
In Lego block diagram programming, we created a sub-function with the "My Blocks" facility.
A sub-functions is called a sub in NQC, e.g.,
task main()
{// ...do some stuff
spinAround(); // this calls the subfunction
// ...do whatever else}
sub spinAround() {OnFwd(OUT_A);
OnRev(OUT_C);
Wait (50);
OnFwd(OUT_A+OUT_C);}
Note that you call a sub-function by referring to its name (see call in main).
In-Class Task:
Write a program with a main task and two sub-functions, spinAround and playMusic (just have it play some sounds). The main function should call the subfunctions three times, using a while loop. You'll need to define a variable for the loop counter.