Get GNU bc to print a newline character

GNU bc is very unconventional. I can't find anything online about how to get it to print a newline character. I'm trying to get it to print the first 16 hexadecimal digits of the sines of the integers from 1 to 30. I'd expect something like this to work:

define mod(x, y) {
    oldscale=scale;
    scale=0;
    result=x%y;
    scale=oldscale;
    return result;
}
obase=16;
x=1;
while (x <= 30) {
    X=2^64*mod(s(x),1)-mod((2^64*mod(s(x),1)),1);
    print X"\n";
    x=x+1;
}

But it doesn't.


Just found another possible problem: if you're using a capital X character, this happens when I try using it in bc:

X=3
(standard_in) 16: illegal character: X
(standard_in) 16: syntax error

Apparently only lower case characters are variables (from the man page: Input numbers may contain the characters 0-9 and A-F. (Note: They must be capitals. Lower case letters are variable names).

So changing to a different lower case character (since there's already another lower case x) would be a good idea.


I just tried some very basic testing, apparently using print in bc makes it not print a trailing newline. Just putting the variable / number on it's own line does print a newline:

$ echo "x=5; print x; print 999; x; 15; print 15; 12345"|bc
59995
15
1512345

So, replacing your print x"\n"; line with just x; should work?

And, using a \n with print should work too, maybe you had a quoting problem... when I tried echoing to bc using double-double-quotes (definitely wrong ;-) or double-quoted with single quoted \ns it fails:

$ echo "x=5; print x; print 999; x; 15; print "15\n\n\n"; 12345"|bc
(standard_in) 1: syntax error
$ echo "x=5; print x; print 999; x; 15; print '15\n\n\n'; 12345"|bc
(standard_in) 1: illegal character: '
(standard_in) 1: illegal character: \
(standard_in) 1: syntax error
(standard_in) 1: illegal character: \
(standard_in) 1: illegal character: \
(standard_in) 1: illegal character: '

But using single quotes for echo, and double-quotes for the \ns it does work

$ echo 'x=5; print x; print 999; x; 15; print "15\n\n\n"; 12345'|bc
59995
15
15


12345

So, also replacing your print x"\n"; line with print "x\n"; should work too?

An informative quote from man bc:

print list
The print statement (an extension) provides another method of output. The "list" is a list of strings and expressions separated by commas. Each string or expression is printed in the order of the list. No terminating newline is printed. Expressions are evaluated and their value is printed and assigned to the variable last. Strings in the print statement are printed to the output and may contain special characters. Special characters start with the backslash character (\). The special characters recognized by bc are "a" (alert or bell), "b" (backspace), "f" (form feed), "n" (newline), "r" (carriage return), "q" (double quote), "t" (tab), and "\" (backslash). Any other character following the backslash will be ignored.