bc

Created: 12 Apr 2024
Updated: 08 Feb 2025
man gnu https://www.gnu.org/software/bc/manual/html_mono/bc.html
man posix https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
source (C) https://github.com/fivepiece/gnu-bc/
faq http://phodd.net/gnu-bc/bcfaq.html
tutorial https://org.coloradomesa.edu/~mapierce2/bc/
wiki https://en.wikipedia.org/wiki/Bc_%28programming_language%29
online https://bc.js.org/

cli

bc [OPTIONS] [FILES]
-q –quiet suppreses welcome message
-l –mathlib enables trigonometric functions, sets scale=20

language

  • Runs interactively (REPL) if you just run it bare "bc"
  • default scale=0, aka integer division
  • in POSIX mode, functions and variables can only be 1 character long
  • undefined variables return 0
  • if/while/for
  • "#" single line comment, "**" multi line comment
  • "auto" for declare local variables
define foo(x) {
  auto pi=3.14
  print "this is 2 to the power of "; x*1; 2^x; pi*2;
  print "\n"
}

functions

length n length in digits of n, including decimals
s n sine
c n cosine
a n arctangent
l n natural logarithm
e n exponential of e to n
j n,m Bessel function of integer order n of x
random - returns a random positive? integer
read - reads value from stdin, returns value read
print s ala Python 2

variables

last last numer output
scale number of decimals (default 0)
obase "output base" (default 10)
ibase "input base"

articles

videos

codebases

snippets

pi

scale=10
4*a(1)

solve

$ solve "4*49+732"
$ cat /usr/local/bin/solve
  #!/bin/sh
  bc << EOF
  scale=4
  $@
  quit
  EOF

sergiosgc/AdventOfCode2021

  • day6 part 1

    for (; i>0; i-=1) {
        n = timer[0]
        for (t=0; t<8; t+=1) timer[t] = timer[t+1]
        timer[8] = n
        timer[6] += n
    }
    for (i=0; i<9; i+=1) result += timer[i]
    print result
    print "\n"
    

implementations