Tag Archives: Math

C Programming Quick Reference

Program Structure / Functions

type func(type1, …); //function prototype
type name; //variable declaration
int main(void){ //main routine
declarations //local variable declarations
/* */ /*Original C comments (block/multiple line comments*/
// //single line comments recognized by most all compilers
int main(int argc, char *argv[]) //main with args
exit(arg); //terminate execution

C Preprocessor

#include <filename> include library file
#include “filename” include user file
#define name text replacement text
#define name(var) text replacement macro Ex: #define max(a,b) ((a)>(b) ? (a) : (b))
#undefine name undefine
# quoted string in replace Ex: #define msg(a) printf(“%s = %d, #a, (a))
## concatenate args and rescan
#if, #else, #elif, #endif conditional execution
#ifdef, #ifndef is name defined, not defined?
defined(name) name defined?
\ line continuation char

Data Type / Declarations

char character (1 byte)
int integer
float, double real number (single, double precision)
short short (16 bit integer)
long long (32 bit integer)
long long double long (64 bit integer)
signed positive or negative
unsigned non-negative modulo 2m
int*, float*,… pointer to int, float,…
enum tag {name1=value1,…}; enumeration constant
type const name; constant (read-only) value
extern declare external variable
static internal to source file
static local persistent between calls
struct tag {…}; Structure
typedef type name; Create new name for data type
sizeof object size of an object (type is size_t)
sizeof(type) size of a data type (type is size_t)


type name=value; initialize variable
type name[]={value1,…}; initialize array
char name[]=”string”; initialize char string


65536L, -1U, 3.0F Long, unsigned, float
4.2e1 exponential form
0, 0x or 0X octal, hexadecimal Ex: 031 is 25, 0x31 is 49 decimal
‘a’, ‘\ooo’, ‘\xhh’ character constant (char, octal, hex)
\n, \r, \t, \b newline, cr, tab, backspace
\\, \?, \’, \” special characters
“abc…de” string constant (ends with ‘\0’)

Pointers, Arrays and Structures

type *name; declare pointer to type
type *f(); declare function returning pointer to type
type (*pf)(); declare pointer to function returning type
void * generic pointer type
NULL null pointer constant
*pointer object pointed to by pointer
&name address of object name
name[dim] array
name[dim1][dim2]… multi-dimensional array


struct tag { structure template
declarations declaration of members
struct tag name create structure
name.member member of structure from template
pointer -> member member of pointed-to structure Ex: (*p).x and p->x are the same
union single object, multiple possible types
unsigned member: b; bit field with b bits

Operators By Precedence

name, member struct member operator
pointer -> member struct member through pointer
++, — increment, decrement
+, -, !, ~ plus, minus, logical not, bitwise not
*pointer, indirection via pointer, address of object
(type) expr cast expression to type
sizeof size of any object
*, /, % Multiply, divide, modulus (remainder)
+, – Add, subtract
<<, >> left, right shift [bit op]
>, >=, <, <= relational comparisons
==, != Equality comparison
& And [bit op]
^ exclusive or [bit op]
| or (inclusive)
&& logical and
|| logical or
expr1 ? expr2 : expr3 Conditional expression
+=, -=, *=, … assignment operators
, Expression evaluation separator

Unary operators, conditional expression and assignment operators group right to left; all others group left to right

Flow Control

; Statement terminator
{} Block delimiters
break; exit from switch, while, do, for
continue; next iteration of while, do, for
goto label; go to
label: statement label
return expr return value from function

Flow Constructions

if (expr1) statement1
        else if (expr2) statement 2
        else statement3
if statement
while (expr)
while statement
for (expr1; expr2; expr3)
for statement
do statement
        while (expr);
do statement
switch (expr) {
        case const1: statement1 break;
        case const2: statement2 break;
        default: statement
switch statement

ANSI Standard Libraries


Character Class Test <ctype.h>

isalnum(c) Alphanumeric?
isalpha(c) Alphabetic?
iscntrl(c) Control character?
isdigit(c) Decimal digit?
isgraph(c) printing character (not including space)?
islower(c) Lower case letter?
isprint(c) Printing Character (Including space)?
ispunct(c) Printing Character except space, letter, digit?
isspace(c) space, formfeed, newline, cr, tab, vtab?
isupper(c) Upper case letter?
isxdigit(c) Hexadecimal digit?
tolower(c) Convert to lower case
toupper(c) Convert to upper case

String Operations <string.h>
s is a string; cs, ct are constant strings

strlen(s) length of s
strcopy(s, ct) Copy ct to s
strcat(s, ct) Concatenate ct after s
strcmp(cs, ct) compare cs to ct
strcmp(cs, ct, n) compare cs to ct, only first n chars
strchr(cs, c) Pointer to first c in cs
strrchr(cs, c) Pointer to last c in cs
memcpy(s,ct,n) Copy n chars from ct to s
memmove(s,ct,n) Copy n chars from ct to s, may overlap
memcmp(cs,ct,n) Compare n chars of cs with ct
memchr(cs,c,n) Pointer to first c in first n char of cs
memset(s,c,n) Put c into first n chars of s

Input / Output <stdio.h>
Standard I/O

stdin Standard input stream
stdout Standard output stream
stderr Standard Errros stream
EOF End of file (type is int)
getchar() Get a character
putchar(chr) Print a character
printf(“format”, arg1, …) Print formatted data
sprintf(s, “format”, ard1, …) Print to string s
scanf(“format”, &name1, …) Read formatted data
sscanf(s, “format”, &name, …) read from string s
puts(s) Print string s

File I/O

FILE *fp; Declare file pointer
fopen(“name”, “mode”) Pointer to named file modes: r (read), w (write), a (append), b (binary)
getc(fp) Get a character
putc(chr, fp) Write to character
fprintf(fp, “format”, arg1, …) Write to file
fscanf(fp, “format”, arg1, …) Read from file
fread(*ptr, eltsize, n, fp) Read and store n elts to *ptr
fwrite(*ptr, eltsize, n, fp) Write n elts from *ptr to file
fclose(fp) Close file
ferror(fp) non-zero if error
feof(fp) non-zero if already reached EOF
fgets(s, max, fp) read line to string s ( < max chars)
fputs(s, fp) Write string s

Codes for Formatted I/O “%-+ 0w.pmc”

Left justify
+ Print with sign
space Print space if no sign
0 Pad with leading zeros
w Min field width
p Precision
        h short
        l long
        L long double
Conversion character:
        d,i integer
        c Single Char
        f Double (printf)
        f Float(scanf)
        o Octal
        p Pointer
        g,G same as f or e,E depending on exponent
        u Unsigned
        s Char string
        e,E Exponential
        lf Double (scanf)
        x,X Hexadecimal
        n Number of chars written
Conversion character:

Variable Argument Lists <stdarg.h>

va_list ap; Declaration of pointer to arguments
va_start(ap,lastarg); Initialization of argument pointer /* lastarg is last named parameter of the function*/
va_arg(ap,type); Access next unamed tag, update pointer
va_end(ap); Call before exiting function

Standard Utility Functions <stdlib.h>

abs(n) Absolute value of int n
labs(n) Absolute value of long n
div(n,d) Quotient and remainder of ints n,d returns structure with div_t.quot and div_t.rem
ldiv(n,d) Quotient and remainder of longs n,d returns structure with ldiv_t.quot and ldiv_t.rem
rand() Pseudo random integer [0,RAND_MAX]
srand(n) Set random seed to n
exit(status) Terminate program execution
system(s) Pass string s to system for execution


atof(s) Convert string s to double
atoi(s) Convert string s to integer
atol(s) Convert string s to long
strtod(s,&endp) Convert prefix of s to double
strtol(s,&endp,b) Convert prefix of s (base b) to long
strtoul(s,&endp,b) Convert prefix of s (base b) to unsigned long

Storage Allocation

malloc(size), calloc(nobj,size) Allocate storge
newptr = realloc(ptr,size); Change Size of storage
free(ptr); Deallocate storage

Array Functions

bsearch(key,array,n,size,cmpf) Search Array for key
qsort(array,n,size,cmpf) Sort Array ascending order

Time and Date Functions <time.h>

clock() processor time used by program Ex: clock()/CLOCKS_PER_SEC is time in seconds
time() Current calendar time
difftime(time2,time1) time2-time1 in seconds (double)
clock_t,time_t Arithmetic types representing times
struct tm Structure type for calendar time comps
        tm_sec Seconds after minute
        tm_min Minutes after hour
        tm_hour Hours since mindnight
        tm_mday Day of month
        tm_mon Months since January
        tm_year Years since 2000
        tm_wday Days since Sunday
        tm_yday Days since January 1
        tm_isdst Daylight savings time flag
mktime(tp) Convert local time to calendar time
asctime(tp) Convert time in tp to string
ctime(tp) Convert calendar time in tp to local time
gmtime(tp) Convert calendar time to GMT
localtime(tp) Convert calendar time to local time
strftime(s,smax,”format”,tp) tp is a pointer to a structure of type tm

Mathematical Functions <math.h>
Arguments and returned values are double

sin(x), cos(x), tan(x) Trig functions
asin(x), acos(x), atan(x), atan2(y,x), atan2(y,x) Inverse Trig functions
sinh(x), cosh(x), tanh(x) Hyperbolic trig functions
exp(x), log(x), log10(x) Exponentials & logs
ldexp(x,n), frexp(x,&e) Exponentials & logs (2 power)
modf(x,ip), fmod(x,y) Division & remainder
pow(x,y), sqrt(x) Powers
ceil(x), floor(x), fabs(x) rounding

Interger Type Limits <limits.h>
32bit Linux system

CHAR_BIT Bits in char (8)
CHAR_MAX Max value of char (SCHAR_MAX or UCHAR_MAX)
CHAR_MIN Min value of char (SCHAR_MIN or 0)
SCHAR_MAX Max signed char (+127)
SCHAR_MIN Min signed char (-128)
SHRT_MAX Max value of short (+32,767)
SHRT_MIN Min value of short (-32,768)
INT_MAX Max value of int (+2,147,483,647)(+32,767)
INT_MIN Min value of int (-2,147,483,648)(-32,767)
LONG_MAX Max value of long (+2,147,483,647)
LONG_MIN Min value of long (-2,147,483,648)
UCHAR_MAX Max unsigned char (255)
USHRT_MAX Max unsigned short (65,535)
UINT_MAX Max unsigned int (4,294,967,295)(65,535)
ULONG_MAX Max unsigned long (4,294,967,295)

Float Type Limits <float.h>
32bit Linux system

FLT_RADIX Radix of exponent rep (2)
FLT_ROUNDS Floating point rounding mode
FLT_DIG Decimal digits of precision (6)
FLT_EPSILON Smallest x so 1.0f + x ≠ 1.0f (1.1E-7)
FLT_MANT_DIG Number of digits in mantissa
FLT_MAX Max float number (3.4E38)
FLT_MAX_EXP Max Exponent
FLT_MIN Min float number (1.2E-38)
FLT_MIN_EXP Min Exponent
DBL_DIG Decimal digits of precision (15)
DBL_EPSILON Smallest x so 1.0 + x ≠ 1.0 (2.2E-16)
DBL_MANT_DIG Number of digits in mantissa
DBL_MAX Max double number (1.8E308)
DBL_MAX_EXP Max Exponent
DBL_MIN Min double number (2.2E-308)
DBL_MIN_EXP Minimum exponent

Arduino Programming Quick Reference

void setup()
void loop()

Control Structures
if (x<7){} else{}
switch (newvar) {
case 1:
case 2:
for (int i=0; i <=255; i++){}
while (X<7){}
do {} while (x<7);
continue;                                              //Go to next in do, for, while loop
return x;                                               //Or return; for voids
goto                                                       //potentially harmful

More Syntax
// Single line comment
/* MultiLine comment */
#define COUPLE 2
#include <avr/pgmspace.h>

General Operators
= Assignment Operator
+ Addition
– Subtraction
* Multiplication
/ Division
% Modulo
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less then or equal to
>= Greater than or equal to
&& And
|| Or
! Not

Pointer Access
& Reference operator
* Dereference operator

Bitwise Operators
& Bitwise and
| Bitwise or
^ Bitwise xor
~ Bitwise not
<< Bitshift left
>> Bitshift right

Compound Operators
++ Increment
— decrement
+= compound addition
-= compound subtraction
*= Compound multiplication
/= Compound division
&= Compound bitwise and
|= Compound bitwise or

true | false
143                                                   //Decimal number
0173                                               //Octal number
0b11011111                            //Binary
0x7B                                              //Hex number
7U                                                  //Force unsigned
10L                                                //Force long
15UL                                            //Force long unsigned
10.0                                               //Forces floating point
2.4e5                                           //240000

Data Types
boolean                                                                                //0,1,false,true
char (‘a’ -128 to 127)
unsigned char (0 to 255)
byte (0 to 255)
int (-32,768 to 32,767)
unsigned int (0 to 65,535)
word (0 to 655word (0 to 65,535))
long (-2,147,483,648 to 2,147,483,647)
unsigned long                                                                 //0 to 4,294,967,295
float                                                                                    //-3.4028235E+38 to                                                                                                                   3.4028235E+38
double                                                                              //same as float)
sizeof(newint)                                                            //returns 2 bytes

char S1[15];
char S2[9]={‘s,’y,’s’,’r’,’e’,’c’,’o’,’n’};
char S#[9]={‘s,’y,’s’,’r’,’e’,’c’,’o’,’n’,’\0′};               //included \0 null termination
char S4[] = “sysrecon”;
char S5[9] = “sysrecon”;
char S6[15] = “sysrecon”;

int newInts[6];
int newPins[] = {2,4,8,3,6};
int newSensVals[6] = {2,4,-8,3,2};


static                                //persists between calls
volatile                           //use RAM
const                               //make read only
PROGMEM               //use flash

Digital I/O
pinMode(pin, [INPUT,OUTPUT])
digitalWrite(pin, value)
int digitalRead(pin)                                        //Write high to inputs to use                                                                                                 pull up res

Analog I/O
int analogRead(pin)                                    //call twice if switching pins from                                                                                       high Z source
analogWrite(pin, value)                          //PWM

Advanced I/O
tone(pin, freqhz)
tone(pin, feqhz, duration_ms)
shiftOut(dataPin, clockPin, [MSBFIRST, LSBFIRST], value)
unsigned long pulseIn(pin,[HIGH, LOW])

unsigned long mills()                               //50 days overflow
unsigned long micros()                         //70 min overflow

constrain(x, minval, maxval)
map(val, fromL, fromH, toL, toH)
pow(base, exponent)

Random Numbers
randomSeed(seed)                               //Long or int
long random(max)
long random(min,max)

Bits and Bytes
bit(bitn)                                                   //bitn: 0-LSB 7-MSB

External Interrupts
attachInterrupt(interupt, function, [LOW,CHANGE,RISING,FALLING])

begin([300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200])
int available()
int read()

EEPROM (#include <EEPROM.h>)
byte read(intAddr)
write(intAddr, newByte)

Servo (#include <Servo.h>)
attach(pin, [min_uS, max_uS])
write(angle)                                                           //0-180
writeMicroseconds(uS)                                //1000 – 2000, 1500 is midpoint
read()                                                                       //0-180
attached()                                                            //Returns boolean

SoftwareSerial (#include <SoftwareSerial.h>)
SoftwareSerial(RxPin, TxPin)
begin(longSpeed)                                           //up to 9600
char read()                                                          //blocks till data
print(newData)                                              //or printLn(newData)

Wire (#include <Wire.h>) //For I2C
begin()                                                                //Join as master
begin(addr)                                                     //Join as slave @ addr
requestFrom(addr, count)
beginTransmission(addr)                       //Step 1
send(newByte)                                             //Step 2
send(char * newString)
send(byte * data, size)
endTransmission()                                    //Step 3
byte available()                                           //Num of bytes
byte receive()                                               //Return next byte