C Cheat Sheet


Main Function

void main(void) {
}

Printf

#include <stdio.h>
void main(void) {
    int i = 1;
    unsigned u = 2;
    long l = 3;
    float f = 4.0;
    double d = 5.0;
    char c = 6;
    unsigned char uc = 7;
    printf("i = %d, u = %u, l = %l, f = %f, d = %lf, c = %c, c = %d, uc = %d\n",
            i, u, l, f, d, c, c, uc);
    printf("print a tab by \t and new line by \n");
}

Scanf

#include <stdio.h>
void main(void) {
   int i;
   printf("Print a prompt for i\n");
   scanf("%d", &i);
}

Conditionals

if(flag) {
   // put some statements here to execute if flag is true (flag != 0)
} 
if(flag) {
   // put some statements here to execute if flag is true (flag != 0)
} else {
   // put some statements here to execute if flag is false (flag == 0)
}
switch(flag) {
    case 0:  // statements
   	break;
    case 1:  // statements
  	break;
    case 2:  // statements
  	break;
    default:  // statements
}

Looping

while(flag) {
    // make sure there is some statement in here to change flag to become false.
}

for(i = 0; i < LAST; i++) {
    // statements
}


Math Functions

#include <math.h>

void main(void) {
    double th = pi/2;    // th is in radians
    double x, y;

    x = cos(th);
    y = sin(th);
    th = atan2(y, x);
}


Creating Functions

int functionname(type1 input1, ... , typeN *output1, ...);     // this is the function prototype with the ;
int functionname(type1 input1, ... , typeN *output1, ...)
{
    *output1 = // some function of the input variables.
    *output2 = // some function of the input varialbles.
    ...
    return(someintvalue);
}