Exponential Power Function

This is my assignment, please look at my program and give me any tips? (I'm not quite sure I did it right). Main is supposed to be sending values to the power function.

Write a prototype and function for calculating powers of numbers.
This version should have an integer return type and take two integer inputs, for the base and the exponent. It should do the following:
• handle negative bases
• return an error on negative exponents (we’re not doing those yet)
• handle zero exponents
Call your function from a nested loop in main(), which calls the function using every combination of negative, zero and positive numbers for both base and exponent. This will test your function without the user having to input all the data.
Any code which calls the library pow() function will lose half of the assignment points.


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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>

using namespace std;

int power (int, int);

int main()
{
	int size = 10;
	int test[size];
	int base;
	
	for (base = -2; base < 4; base += 2)
	{
		for (int expon = -2; expon < 4; expon += 2)
		{
			cout << base<< "  " << expon << " " << power(base,expon) << endl;
		}
	}
	
	cout << endl;
	
	return 0;
}

int power (int num, int raisedTo)
{
    int product;
    
    if (raisedTo < 0)
    {
       cout << "Please enter a non negative exponent. " << endl; 
    }
        
    else if (raisedTo == 0)
    {
         product = 1;
         return product;
    }

    while (num > 0)
    {
          
          for (num = num; num <= raisedTo; num++)
          {
               product = num * num;
               return product;
          }  
    }

    while (num <= -1)
    {
       if(raisedTo % 2 == 0)
       {
          for (num = num; num <= raisedTo; num++)
          {
              product = num * num;
              return product;
          }
       }
       else 
           for (num = num; num <= raisedTo; num++)
           {
               product = num * num * -1;
               return product;
           }
       
       
    }
    
    
	
}
well your code looks complicated - you only need one loop

something like this

1
2
3
product = 1;
for(i=0;i<raisedTo;++i)
  product *= num;


Topic archived. No new replies allowed.