Skip to content
Physics and Astronomy
Home Our Teaching Resources C programming silly1.html
Back to top

A silly example

These two fragments of code both calculate the distance from the origin of a point on a plane with gradient 1 in both the x and y directions, but one is much clearer than the other:

Clear

// Calculate the height of a plane of gradient 1
// in both the x and y directions.
#include <stdio.h>
#include <math.h>
int main() {
  double x, y, z, distance;

  x = 2.1;
  y = 1.3; 
  z = x + y;
  distance = sqrt(x*x + y*y + z*z);
  printf("Distance; %g\n", distance);
   
 // See what happens now
  x = 10.0;
  y = y + x;
  printf("Distance; %g\n", distance);
  
  // More code here...
  return 0;
}
Step through this code


Unclear

 double variable1, variable2, variable3;
 double i_feel_like_a_banana;

  variable1 = 2.1;
  variable2 = 1.3;
  variable3 = variable1 + variable2;
  i_feel_like_a_banana = sqrt(variable1*variable1 
    + variable2*variable2 + variable3*variable3);

  variable1 = 10.0;
  variable2 = variable2+ variable1;
  printf("Distance; %g\n", i_feel_like_a_banana);

  // More code here...
Step through this code


                                                                                                                                                                                                                                                                       

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