Doing It All Again
The user of the "squares" program doesn't get much for the effort of running it. One little calculation and the program considers its work to be done. If the user had a few calculations to do, then they would have to keep running the program over and over again. Luckily, we can make that process easier for them.
The GOTO statement will allow program execution to branch to line with a specified label. Branching can be forward or backward. Our squares program can be made a little more useful by the addition of the following line:
40 GOTO 10
Now, instead of the program terminating when it has calculated a square, it will instead go back to line 10, which prints the "Think of a number" prompt, and continue from there. So the prompt will appear again, the user will be asked for another number to be stored in N (overriding what was there before), the square will be calculated, and the GOTO will be encountered again. This is what's called an infinite loop, because it will continue ad infinitum until the user breaks out of the program.
We can take control ourselves instead of relying on the user to break out of the program. The IF command allows decisions to be made. Line 40 could be rewritten as:
40 IF N<>0 THEN GOTO 10
This would go back to line 10 only if the number entered by the user (N) is not 0; if the user enters 0 then its square will be printed but the program will then stop. The comparison works the same as in mathematics, except that some of the operators are different due to the limitation of keyboards and character sets. The six operators you can use are: =, <, >, <> (meaning ≠), <= (meaning ≤) and >= (meaning ≥). You can also use >< for ≠ too.
The statement can be another IF, allowing two comparisons to be made, the final statement only being executed only if both comparisons are true. The following program asks for a number from 1 to 100, and verifies that the number is valid:
10 PRINT "Enter a number from 1 to 100" 20 INPUT N 30 IF N>=1 THEN IF N<=100 THEN PRINT "That is a valid number"
Next: Storing Calculation Results
Comments