Skip to content
Physics and Astronomy
Home Our Teaching Resources C programming A short example
Back to top

Introduction to C - a complete example

This example should give us enough to understand the following example, although there are a few issues we will want to come back to in the next lecture:
//
// Demonstrate the trigonometric identity
// cos(a+b) equals cos(a)*cos(b) - sin(a)*sin(b)
//
#include <stdio.h>
#include <math.h>


int main() {
  double a, b, cos_a_plus_b, error;

  a = 0.707;  // Random values
  b = 0.1234;

  cos_a_plus_b = cos(a) * cos(b) - sin(a) * sin(b);

  error = cos_a_plus_b - cos(a+b);

  printf("I calculate cos(%g) to be %g\n", a + b, cos_a_plus_b);
  printf("with an error of %g\n", error);

  return 0;
}
Step through this code

 

Exercise

Answer the following questions before reading the next section:

  • What does the code do? When you think you know step through the program to see if you are right.
  • Are there any things about it that make it easier to understand?
  • What would the code do if instead of calling the variables a, b and cos_a_plus_b we had called them mummy_bear, daddy_bear and baby_bear? Try it and see.
  • Why do you think we didn't?

Things to notice

  • The (fairly short) comment at the top tells us what is going on.
  • We include the file <stdio.h> to use the printf() and the file <math.h> for sin() and cos()
  • We have used the same variable names "a" and "b" inside the code as we did in the comment. Usually the context gives us an idea of a sensible name for a variable. (We could have used alpha and beta as our variable names instead.)
  • Observe the ridiculously obvious name "cos_a_plus_b". We could have called it "cos_a_b" or "cosab" but you should avoid generic names like "result" or worst of all "c"! What would those names have told you?
    Test cells that should be zero are also a great check to have in spreadsheets.
  • We have included a test and that we have made the test equal to zero for the precise case. This means that the test actually tells us whether it has worked OK, that's what a test is for!
  • We have used correct indentation and blank lines.

On my machine the program prints:

I calculate cos(0.8304) to be 0.674581
with an error of -1.11022e-16
Log in
                                                                                                                                                                                                                                                                       

Validate   Link-check © Copyright & disclaimer Privacy & cookies Share
Back to top