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}}: 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.
<lang commodorebasic>10 N = 5 : GOSUB 100
 
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.
30 N = 9000 : GOSUB 100
 
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))
20 N = 50 :30 GOSUB 100
110 B$ = ""
17040 PRINT N"-> "B$
120 FOR N1 = N2 TO 0 STEP 0
50 GOTO 10
130 : N2 = INT(N1 / 2)
60 DATA 5, 50, 9000, -1
140 : B$ = STR$(N1 - N2 * 2) + B$
4070 END
150 : N1 = N2
90 REM *** SUBROUTINE: CONVERT DECIMALINTEGER IN N TO BINARY STRING B$
160 NEXT N1
110100 B$ = ""
170 PRINT B$
100110 N2FOR N1 = ABS(INT(N)) TO 0 STEP 0
180 RETURN</lang>
140120 : B$ = MID$(STR$(N1 - N2 *AND 1),2) + B$
130 : N2N1 = INT(N1 / 2)
160140 NEXT N1
180150 RETURN</lang>
 
{{Out}}
<pre>
15 0-> 1101
150 1-> 0 0 1 0110010
9000 -> 10001100101000
1 0 0 0 1 1 0 0 1 0 1 0 0 0
</pre>
 
1,479

edits