error: expected unqualified-id before 'if'

Your if statement needs to be inside a function. Presumably inside loop(), just after:

  cm = microsecondsToCentimeters(duration);

Please remember to use ... tags when posting code. See point 6 in http://arduino.cc/forum/index.php/topic,97455.0.html