Advertisements

**bc** - an arbitrary precision calculator language.

- bc [ -hlwsqv ] [long-options] [ file ... ]]

Arithmetic operations are the most common in any kind of programming language. Unix or linux operating system provides the bc command for doing arithmetic calculations.

**bc** starts by processing code from all the files listed on the command line in the order listed. After all files have been processed, bc reads from the standard input.

Tag | Description |
---|---|

-h --help |
Print the usage and exit. |

-i --interactive |
Force interactive mode. |

-l --mathlib |
Define the standard math library. . |

-w --warn |
Give warnings for extensions to POSIX bc. |

-s --standard |
Process exactly the POSIX bc language. |

-q --quiet |
Do not print the normal GNU bc welcome. |

-v --version |
Print the version number and copyright and quit. |

**EXAMPLE-1:**

Finding Sum of Two expressions

$ echo "2+5" | bc

output:

7

**EXAMPLE-2:**

Difference of Two numbers

$ echo "10-4" | bc

output:

6

**EXAMPLE-3:**

Multiplying two numbers.

$ echo "3*8" | bc

output:

24

**EXAMPLE-4:**

Dividing two numbers

When you divide two numbers, the bc command Ignores the decimal part and returns only the integral part as the output.

$ echo "2/3" | bc

output:

0

$ echo "5/4" | bc

output:

1. **EXAMPLE-5:**

Use the scale function to specify the number of decimal digits that the bc command should return.

$ echo "scale=2;2/3" | bc

output:

.66

**EXAMPLE-6:**

Finding the remainder using modulus operator

$ echo "6%4" | bc

output: 2

**EXAMPLE-7:**

Using exponent operator

$ echo "10^2" | bc

output: 100

Here the expression is evaluated as 10 to the power of 2.

**EXAMPLE-8:**

Assigns 10 to the variable and prints the value on the terminal.

$ echo "var=10;var" | bc

output:

10

Increment the value of the variable by 5 $ echo "var=10; var+=5;var" | bc 15

**EXAMPLE-9:**

Logical operators are also mostly used in conditional statements. The result of the logical

operators is either 1 (True) or 0 (false) ! expr : Result is 1 if expr is 0.

$ echo "4 && 10" | bc

output: 1

$ echo "0 || 0" | bc

output: 0

**EXAMPLE-10:**

Conditional statements are used to take decisions and execute statements based on these decisions.

$ echo 'if(1 == 2) print "true" else print "false"' | bc

output: false