I want to write this function integerPower(base, exponent) that return the value of base^exponent For instance integerPower(3, 4) = 3*3*3*3

The function has two parameters my question is how can I use the for loop to control the calculation? It's not that hard to use the for loop when the function has one parameter, but with two parameters I little bit confused by that.

Recommended Answers

All 3 Replies

I want to write this function integerPower(base, exponent) that return the value of base^exponent For instance integerPower(3, 4) = 3*3*3*3

The function has two parameters my question is how can I use the for loop to control the calculation? It's not that hard to use the for loop when the function has one parameter, but with two parameters I little bit confused by that.

I suggest that you approach this as a multi-step process.

1) Write an "empty" function definition that shows the type the function returns and the types of each of the parameters. This might be a good time to think about what values of exponent you are going to accept. Only positive integers? All integers? Or all reals?
2) Then add any local variables that you know will need to write the function.
3) Then add the for statement you will need to calculate the integerPower(). For statements are used to define loops that execute 0 or more times and are natural if you are going to count the number of loops. (Yes, they do not have to just be used for that but that is where they are a natural fit.) Which of your parameters represents the count of the number of times through the loop? (If you were implementing your example with paper and pencil, how would you do it?)
4) What are you going to return from the function?
5) What other local variables do you need to implement the "stuff" you did in steps 3 and 4?

If you do steps 1) and 2) and make an attempt at step 3), we (including me) can help you by giving comments or corrections on your attempt. But this will show you are making an effort. Most forums avoid giving out fully coded examples so that the person asking is actually going to learn something.

I don't seem to understand the difficulty. Can you do the task without using a function? If so, why would a function cause a problem?

Thanks guys, I solved the problem.

I am writing a function with floor just like this, y = floor(x + .5); I did it in dev c++ everything seemed to work fine. But, when I did in CodeBlock, it states that floor must be declared.

I am rounding x and assigning it to y.

Sorry, I realized what was wrong. I forgot to include the #include <math.h> header.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.