Binary digits: Difference between revisions
→{{header|Commodore BASIC}}: make subroutine more general (create string, no print), use READ loop with DATA for demo, add comment on FOR STEP 0 loop.
(→{{header|Commodore BASIC}}: Add output) |
(→{{header|Commodore BASIC}}: make subroutine more general (create string, no print), use READ loop with DATA for demo, add comment on FOR STEP 0 loop.) |
||
Line 1,230:
==={{header|Commodore BASIC}}===
Since the task only requires nonnegative integers, we use a negative one to signal the end of the demonstration data.
20 N = 50 : GOSUB 100▼
Note the <tt>FOR N1 =</tt> ... <tt>TO 0 STEP 0</tt> idiom; the zero step means that the variable is not modified by BASIC, so it's up to the code inside the loop to eventually set <tt>N1</tt> to 0 so that the loop terminates – like a C <tt>for</tt> loop with an empty third clause. After the initialization, it's essentially a "while N1 is not 0" loop, but Commodore BASIC originally didn't have <b>while</b> loops (<tt>DO WHILE</tt> ... <tt>LOOP</tt> was added in BASIC 3.5). The alternative would be a <tt>GOTO</tt>, but the <tt>FOR</tt> loop lends more structure.
40 END▼
<lang gwbasic>10 READ N
90 REM *** SUBROUTINE: CONVERT DECIMAL TO BINARY▼
20 IF N < 0 THEN 70
100 N2 = ABS(INT(N))▼
110 B$ = ""▼
50 GOTO 10
130 : N2 = INT(N1 / 2)▼
60 DATA 5, 50, 9000, -1
140 : B$ = STR$(N1 - N2 * 2) + B$▼
160 NEXT N1▼
▲170 PRINT B$
180 RETURN</lang>▼
{{Out}}
<pre>
9000 -> 10001100101000
</pre>
|