it's rather simple...you want to use functions to solve a problem and one problem only...you want to use loops to HELP solve your problem....although there is already a function that resolves exponents, i'll re-invent the wheel to demonstrate how when to use these 3 structures...this function excepts 2 integer parameters and returns one integer...the first parameter is the mantissa and the second parameter is the exponent.
NOTE: if you actually run this 'program' (which i have not ran myself), don't use very large numbers, as you may know, exponential numbers can get large very quickly and variables of type 'int' can only store a value not much larger than 32,000
Code:
int resolveExponent(int mantissa, int exponent)
{
int solution; //the return variable
if(exponent == 0) //any number to the power of zero is 1 (i think)
return 1;
if(exponent == 1) //any number to the power of 1 is itself (again, i think)
return mantissa;
//now we use a loop to repeat the multiplication
//because a number to the power of x is the number times itself x times
//i'm sure you know this, but 3 to the power of 3 = 3 * 3 * 3
//but you don't want to type 3*3*3 everytime you want the number 3 to the 3rd
//this is a for loop... the first part says initialize i to zero..this only happens once
//the entire loop. the second part says perform the action within this loop until
// i meets the condition "i is less than or equal to exponent"...the third part says
// increment i (i++ is the same as i = i + 1)...the second and third part occur every pass
//through this loop
for(int i = 0; i <= exponent; i++)
{
solution = solution * mantissa;
}
return solution;
}
int main()
{
//now instead of doing this (below) everytime when want the exponential value
//of a number
/* int mantissa = 3;
int exponent = 3;
for(int i = 0; i <= exponent; i++)
{
solution = solution * mantissa;
}*/
//we can simply do this
int x = resolveExponent(3, 3);
//then, maybe we wanted to do this
x = resolveExponent(x, x);
return 0;
}
and again without the over commenting
Code:
int resolveExponent(int mantissa, int exponent)
{
int solution;
if(exponent == 0)
return 1;
if(exponent == 1)
return mantissa;
for(int i = 0; i <= exponent; i++)
{
solution = solution * mantissa;
}
return solution;
}
int main()
{
int x = resolveExponent(3, 3);
x = resolveExponent(x, x);
return 0;
}
i hope this helps you....
remember though, you only want your functions to solve one problem and one problem only...if the function needs to solve a sub problem then you should probably split that into another function (or use recursion, but don't worry about recursion yet, it's rather confusing)...