|
Variables are fundamental, and we will use them throughout these notes. Here are two ways (among many) of using variables.
Use 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. |
Use 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;The quadratic formula has been expanded out into small parts. 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. |
How can variables make a program more readable? Answer
How can variables make a program more efficient? Answer
|