4C. Some Uses of Variables

Variables are fundamental, and we will use them throughout these notes. Here are two ways of using variables that might not immediately come to mind.

Using variables to avoid computing something twice

Sometimes you want to use the value of an expression in two places, but you only want to compute the expression's value once. That is just a matter of storing the result of the expression in a variable so that the program remembers it. The next item has an example.


Using variables to make programs more readable

Some expressions are long and complicated. Using variables can simplify them. For example, imagine computing the two solutions for x to equation ax2 + bx + c = 0, where you know a, b and c. The following does the job.

  double disc  = b*b - 4*a*c;
  double s     = sqrt(disc);
  double twoa  = 2*a;
  double soln1 = (-b + s)/twoa;
  double soln2 = (-b - s)/twoa;
Notice that s is computed once but used twice. Variable disc is just used to shorten an expression. (You also might want to test whether disc ≥ 0, since otherwise the expression sqrt(disc) causes an error.



Exercises

  1. How can variables make a program more readable? Answer

  2. How can variables make a program more efficient? Answer