Loops/Nested: Difference between revisions
Content added Content deleted
m (→{{header|J}}: remove unnecessary value) |
(→{{header|S-BASIC}}: Added alternate approach avoiding GOTO) |
||
Line 3,592: | Line 3,592: | ||
0done if i > ROWS then print "target value"; MAXVAL; " not found!" |
0done if i > ROWS then print "target value"; MAXVAL; " not found!" |
||
end |
|||
</lang> |
|||
The use of GOTO, while convenient, is at odds with S-BASIC's structured programming ethos. Adding a boolean flag to the inner loop allows us to avoid the GOTO. Although S-BASIC has no explicit boolean variable type, integers, real numbers, characters, and strings can all be used as boolean variables. For integers, 0 is false and -1 is true. For real variables, 0 is false and any non-zero value is true. For characters, 'T', 't', 'Y', and 'y' are evaluated as true, while 'F', 'f', 'N', and 'n' are evaluated as false. Strings follow the same rule, with only the first character considered. |
|||
<lang BASIC> |
|||
$constant ROWS = 10 |
|||
$constant COLUMNS = 10 |
|||
$constant TOPVAL = 20 |
|||
$constant TRUE = FFFFH |
|||
$constant FALSE = 0H |
|||
var i, j, done = integer |
|||
dim integer table(ROWS, COLUMNS) |
|||
rem - populate table using nested FOR..NEXT loops |
|||
for i=1 to ROWS |
|||
for j=1 to COLUMNS |
|||
table(i, j) = int(rnd(1) * TOPVAL) + 1 |
|||
next j |
|||
next i |
|||
rem - show results using nested WHILE..DO loops |
|||
i = 1 |
|||
done = FALSE |
|||
while i <= ROWS and not done do |
|||
begin |
|||
j = 1 |
|||
while j <= COLUMNS and not done do |
|||
begin |
|||
print using "## "; table(i, j); |
|||
if table(i, j) = TOPVAL then done = TRUE |
|||
j = j + 1 |
|||
end |
|||
print |
|||
i = i + 1 |
|||
end |
|||
if i > ROWS then print "Target value of"; TOPVAL; " not found!" |
|||
end |
end |
||
</lang> |
</lang> |
||
{{out}} |
{{out}} |
||
The output is the same for both programs. |
|||
<pre> |
<pre> |
||
1 2 7 20 |
1 2 7 20 |