B (programming language): Difference between revisions

Content deleted Content added
No edit summary
Examples: Corrected the code to match with the image of the original printed document (https://www.bell-labs.com/usr/dmr/www/kbman.pdf). For example, spaces are never used after keywords such as if and while, and code is indented three columns.
Tags: Mobile edit Mobile web edit
Line 83:
/* The following function will print a non-negative number, n, to
the base b, where 2<=b<=10. This routine uses the fact that
in the ASCIIANSCII character set, the digits 0 to 9 have sequential
code values. */
 
printn(n, b) {
extrn putchar;
auto a;
/* Wikipedia note: the auto keyword declares a variable with
automatic storage (lifetime is function scope), not
"automatic typing" as in C++11. */
 
if (a = n / b) /* assignment, not test for equality */
printn(a, b); /* recursive */
putchar(n % b + '0');
}
</syntaxhighlight>
Line 102:
/* The following program will calculate the constant e-2 to about
4000 decimal digits, and print it 50 characters to the line in
groups of 5 characters. The method is simple output conversionconver-
sion of the expansion
1/2! + 1/3! + ... = .111....
where the bases of the digits are 2, 3, 4, . . . */
 
main() {
extrn putchar, n, v;
auto i, c, col, a;
 
i = col = 0;
while(i<n)
v[i++] = 1;
while(col<2*n) {
a = n+1;
c = i = 0;
while (i<n) {
c =+ v[i] *10;
v[i++] = c%a;
c =/ a--;
}
 
while(col<2*n) {
putchar(c+'0');
a = n+1;
if(!(++col%5))
c = i = 0;
putchar(col%50?' ': '*n');
while(i<n) {
}
c =+ v[i] *10;
putchar('*n*n');
v[i++] = c%a;
c =/ a--;
}
putchar(c+'0');
if(!(++col%5))
putchar(col%50?' ': '*n');
}
putchar('*n*n');
}
 
v[2000];
n 2000;