**Simple arithmetic.**

Addition and subtraction work intuitively, using + and -. Multiplication is performed using * and division
using /. The one principle to remember is 'precedence'. When you combine arithmetic calculations in one
statement, it can lead to unexpected results.

`2 + 3 * 4 = 14`

If you were expecting 20, you are reading the arithmetic as you would enter it into
a calculator. The compiler uses precedence rules to resolve the ambiguity in the example calculation.
Multiplication and division have the higher precedence, so the compiler actually performs `3*4`

before the ` 2 +`

in the example. To make sure your calculation works as expected, use
parentheses:

`(2 + 3) * 4 = 20`

`2 + (3 * 4) = 14`

**Modulus**

Many computerised systems use numerical codes to represent real-world products. To prevent simple typing
errors causing the selection of the wrong product, these codes are not sequential. Instead, the first or final
digit of the code is calculated from the rest of the digits to create a checksum. Validation of this checksum
is possibly the most frequent arithmetic calculation because it is used every time a barcode is scanned. An
important part of the calculation is usually the modulus operator which calculates the remainder of a division.
Instead of calculating a floating point number to express the fraction, the modulus operator returns the
remainder.

`12 % 3 = 0; // (12 / 3 = 4.00000 or 4 with no remainder)`

`13 % 3 = 1; // (13 / 3 = 4.33333 or 4 with a remainder of 1)`

**Mathematical functions**

The standard library provides functions for angles, logs, exponentials, powers and square roots.

Function | Description |
---|---|

sin(x),asin(x),sinh(x) | sine, arcsine, hyperbolic sine of value x |

cos(x),acos(x),cosh(x) | cosine, arccosine, hyperbolic cosine of x |

tan(x),atan(x),tanh(x) | tangent, arctangent, hyperbolic tangent |

log(x), log10(x) | natural base or base-10 logarithm of x |

exp(x) | e to the power of x |

pow(x,y) | x to the power y |

sqrt(x) | square root of x |

Remember that most of these functions will return a `float`

value and
that sqrt(-1) is not valid in simple arithmetic!

**Number and text conversions**

printf can convert digits into strings and C also provides functions to convert
`char string[] = "100";`

into `int digit = 100;`

.

`char string[] = "100";`

int digit = atoi(string);

`atoi()`

converts an **a**lphanumeric string **to** an **i**nteger.
Other examples include:

`float fraction = atof(string);`

long number = atol(string);

string = itoa(100);

string = ftoa(100.00);

string = ltoa(number);

This is part of www.codehelp.co.uk Copyright © 1998-2004 Neil Williams

See the file about.html for
copying conditions.