Now you can define the power_of_2
function using a for
loop
instead of a while
loop. The initialization expression,
counter = n
, assigns the value of the parameter n
to
counter
. Then, as long as the value of counter
is not 0, the
value of result
, whose initial value is 1, is multiplied by 2 and
the value of counter
is decremented by 1.
int power_of_2 (int n) { int counter, result = 1; for (counter = n; counter; counter = counter - 1) result = 2 * result; return result; }
Augmented assignment operators reassign a variable to a value that your program obtains by combining the variable's current value with an expression's value via addition, subtraction, multiplication, or division. The following diagram illustrates how assignment using an augmented assignment operator differs from ordinary assignment:
variable name = variable name operator expression | | | *-----------------* v variable name operator= expression
For example, you can rewrite result = result * 2
in this
way:
result *= 2
Even though this shorthand gives you a perfectly valid way to multiply and
reassign, you may choose to write result = result * 2
, which you see
throughout this book, on the ground that result = result * 2
stands
out more clearly as a reassignment operation.