PHYS 252

Basic C Commands (see C Reference Card (pdf) for more)

Program Structure/Functions

type fnc(type1, ...)
type name:
main() {   
   declarations
   statements

}
type fnc(arg1, ...) {
   declarations
   statements

return value;
}

/* */    :    comment

C Preprocessor

include library file: #include <filename>
include user file: #include "filename"
replacement text: #define name text

Data Types/Declarations

char, int, float, double

Initialization

initialize variable: type name = value
initialize array: type name[]= {value1, ...}
initialize char string: char name[]= "string"

Pointers and Arrays

declare pointer to type :    type *name
declare function returning pointer to type :    type *f()
declare pointer to function returning type:   type (*pf)()
object pointed to by pointer:   *pointer
address of object name:   &name
array: name[dim]
multi-dim array: name[dim1][dim2]...

Operators

++,--, !, *pointer, &name, (type) expr, sizeof
*, /, %
+, -
>, >=, <, <=
==, !=
&&
||
+=, -=, *=

Flow of Control

statement terminator:   ;
block delimeters:   { }
exit from while, do, for:   break
next iteration of while, do, for:   continue
return value from function:   return expr

if (expr) statement
else if (expr) statement
else statement

while(expr)
  statement

for (expr1; expr2; expr3)
  statement

Input/Output <stdio.h>

print to screen: printf("format", arg1, ...)
read from screen: scanf("format", &name1, ...)
declare file pointer: FILE *fp
open file and attach to pointer fp: fp = fopen("name", "mode")
    modes: r (read), w (write), a (append)
close file: fclose(fp)
write to file: fprintf(fp, "format", arg1, ...)
read from file: fscanf(fp, "format", arg1, ...)
Format Codes:
    %d integer, %f float, %lf double
    %15.2f example for float with field width of 15 and 2 digits after decimal

Math Functions <math.h>

sin,cos,tan,sinh,cosh,tanh,exp,log,log10
atan2(y,x), pow(x,y), sqrt, ceil, floor