Originally Posted by
Lucid003
She includes the following example:
*p = (interest + interest / (pow(1 + interest,months) -1) ) *p;
p++;
I assume the example is actually something like;
Code:
*p = (interest + interest / (pow(1 + interest,months) -1) ) * (*p);
which (for simplicity), I'll re-express as
Code:
*p *= (interest + interest / (pow(1 + interest,months) -1) );
I cannot figure out how to successfully include that in a for loop.
A literal approach would be;
Code:
void calculatePayment( double *p )
{
for ( int i = 0; i < 5; i++)
{
*p *= ( .05 + .05 / (pow(1 + .05, 36) -1 ) );
++p;
}
}
which can be adjusted to;
Code:
void calculatePayment( double *p )
{
for ( int i = 0; i < 5; ++i, ++p)
{
*p *= ( .05 + .05 / (pow(1 + .05, 36) -1 ) ) ;
}
}
or, if you want to eliminate the integer counter and play only with pointers;
Code:
void calculatePayment( double *p )
{
double *end;
for (end = p + 5; p != end; ++p)
{
*p *= ( .05 + .05 / (pow(1 + .05, 36) -1 ) );
}
}
p+5 gives the address of p[5] and you simply increment the pointer p until that address is reached. And, whatever you do, do NOT try to dereference p when it is equal to end (unless p refers to an array with more than 5 elements).
Pointers are wonderful and mysterious things.
You might also want to consider that this is equivalent....
Code:
void calculatePayment( double *p )
{
for ( int i = 0; i < 5; i++)
{
*(p + i) *= ( .05 + .05 / (pow(1 + .05, 36) -1 ) );
}
}
as (for a pointer p) *(p + i) and p[i] are the same thing (they identify the i'th element of p).
One of the more obscure corners of C and C++ is this: i[p] is the same as p[i].