iPow function does not execute

Hello I need help my iPow function does not seem to calculate the inputs.
The program is just a simple program to calculate x^n . However I need to use a function.The output it generates now is exactly the same as the integer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include <iostream>
using namespace std;

float x, answer;
int i, n;

float iPow()
{
    answer =1;
    for( i=1; i <=n ; i++)
    {
        answer *= x;
        return answer ;
    }
}

int main()
{
    cout << " Enter a number and a non-negative integer " << endl;
    cin >> x >> n;
    cout << x << " to the power " << n << " is " << endl;
    cout << iPow() << endl;

    return 0;

}
You have to move the return outside of the loop. Currently, it will only go through one iteration before leaving the function.
firstly you should be passing parameters into your function, and not use global variables.
See
http://www.cplusplus.com/doc/tutorial/functions/

the main reason it's not working though is this:

1
2
3
4
5
    for( i=1; i <=n ; i++)
    {
        answer *= x;
        return answer ;
    }


Because you call return inside your for loop, you are not actually allowing your for loop to loop! It exits immediately.


So roughly you'd want something like this:
1. delete your nasty globals from lines 4 and 5.
2. do this:
1
2
3
4
5
6
7
8
9
10
float iPow(float x, int n)
{
    int answer =1;
    for(int i=1; i <=n ; i++)
    {
        answer *= x;
        
    }
    return answer ; // <-- allow your for loop to do it's thing.
}


3. call like this:
cout << iPow(x,n) << endl;


something like that.
Last edited on
Thanks guys appreciated.

It works fine now.
Topic archived. No new replies allowed.