custom pow() function

I need to make a variation of the pow() function for a homework assignment.

These are the requirements:

"Using a for loop, write code that will compute the result of an int raised to the power of another int. For example, your for loop should use two variables, one for the base and one for the exponent. It should then calculate the base raised to the exponent. 2 raised to the power of 2 should output 4, 2 raised to 8 should output 256, etc. Ensure your code meets these requirements and then paste it in the response section below:"

"Contains a variable for the base
Contains a variable for the exponent
Uses a for loop to perform the power function
Outputs the result to the console window"

This is the code I have right now:
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
74
75
76
77
// Osman Zakir
// 12 / 28 / 2016
// raise_to_power.cpp
// edx.org Introduction to C++ - Control Flow Peer Review
// Requirements:
/**
 * Contains a variable for the base
 * Contains a variable for the exponent
 * Uses a for loop to perform the power function
 * Outputs the result to the console window
 */

#include <iostream>
#include <stdexcept>

int raise_to_power(int number, int exp);
void print_result(const int result, const int number, const int exp);

int main()
{
	int number = 0, exp = 0, result = 0;
	using namespace std;
	try
	{
		number = 2, exp = 2;
		result = raise_to_power(number, exp);
		print_result(result, number, exp);
	}
	catch (const runtime_error &e)
	{
		cerr << "Error: " << e.what() << endl;
		if (number <= 0)
		{
			cout << "Provide a positive value for number to raise to power: ";
			cin >> number;
			cin.ignore();
			result = raise_to_power(number, exp);
			print_result(result, number, exp);
		}
		if (exp <= 0)
		{
			cout << "Provide a positive value for exponent: ";
			cin >> exp;
			cin.ignore();
			result = raise_to_power(number, exp);
			print_result(result, number, exp);
		}
	}
}

int raise_to_power(int number, int exp)
// pre-condition: both the number and the exponent should be positive
{
	using namespace std;
	if (number <= 0 || exp <= 0)
	{
		throw runtime_error("bad argument to raise_to_power()");
	}
	else if (number <= 0 && exp <= 0)
	{
		throw runtime_error("bad argument to raise_to_power()");
	}
	int result = 0;
	for (int i = 1; i <= number; ++i)
	{
		result = i;
		result *= exp * exp;
	}
	return result;
// post-condition: the result should be positive
}

void print_result(const int result, const int number, const int exp)
{
	using namespace std;
	cout << number << " raised to the power of " << exp << " is " << result << "\n";
}


I need helping fixing the bug and also in making it less complicated if possible. Thanks in advance.

Edit: Okay, never mind on the bug. I fixed it from looking other code on this site.

It works like this:
1
2
3
4
5
6
int result = 1;
for (int i = 0; i < exp; ++i)
{
	result *= number;
}
return result;


Everything else is the same as before, though, so I'd like to know of a good way to make the code in main() more simple (in the catch block, I mean). It has to still handle the exception like it does now, but the code should just be less complicated.
Last edited on
You should not restrict the base or the exponent to a positive number. It's perfectly legal for either one to be negative, although this means that the result must be a double. Once you do this, you won't need to throw or catch any exceptions.

You don't need print_result(). Just move line 76 to your main program.
Last edited on
- return value should be double (or maybe even long, long long?) as int raised to power int can go beyond max int limit
- using namespace std inside print_result() (and/or elsewhere) invites trouble: http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-
practice
- identify that the function throws also in the declaration
- need much more input validation beyond just checking for negative numbers (incidentally 0 is considered an integer in maths and so it should not be excluded) so, putting everything together, a regex based approach:
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
#include <iostream>
#include <string>
#include <sstream>
#include <sstream>
#include <stdexcept>
#include <regex>

bool raise_to_power() throw (const std::runtime_error);

int main()
{
    bool fQuit = false;
    while (!fQuit)
    {
        try
        {
            if(raise_to_power())
            {
                fQuit = true;
                break;
            }
        }
        catch(const std::runtime_error & e)
        {
            std::cout << e.what() << '\n';
            std::cout << "Try again\n";
        }
    }
}


bool raise_to_power() throw (const std::runtime_error)
{
        std::string number{};
        std::cout << "Enter number: \n";
        getline(std::cin, number);
        std::cout << "Enter exponent: \n";
        std::string exponent{};
        getline(std::cin, exponent);
        std::regex r("(\\^-)?[[:digit:]]+");
        int result = 1;
        if((std::regex_match(number,r)) && (std::regex_match(exponent, r)))
        {
            std::stringstream stream_num(number);
            std::stringstream stream_exp(exponent);

            int int_num {}, int_exp{};
            stream_num >> int_num;
            stream_exp >> int_exp;
            for (int i = 0; i < int_exp; i++)
            {
                result *= int_num;
            }

                std::cout << result << '\n';
                return true;
        }
        else
        {
            throw std::runtime_error("bad argument to raise_to_power()");
            return false;
        }
}

PS: if you accept dhayden's suggestion to include negative numbers as well you just have to edit the std::regex object, that's all
PPS: you could also throw std::out_of_range and set up another catch block for that

Last edited on
Been digging around exception handling, it seems general opinion is that the throw keyword in the function signature does not add much:
http://stackoverflow.com/questions/1055387/throw-keyword-in-functions-signature

Then I thought what about 'noexcept'? Here too, it appears, that the opinion is mixed and case for the keyword is primarily related to move semantics:

http://stackoverflow.com/questions/10787766/when-should-i-really-use-noexcept
https://akrzemi1.wordpress.com/2014/04/24/noexcept-what-for/

So ... OP you can disregard my 3rd suggestion if you wish
closed account (48T7M4Gy)
This is one way and by playing around with the disposition of the catch blocks a workable loop can be made to work. As it stands if you make a sign error in the second input you have to renew both numbers.

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
#include <iostream>

int main()
{
    int number1 = 0, number2 = 0;
    bool keep_going = true;
    
    while(keep_going == true)
    {
        try
        {
            std::cout << "1st number: ";
            std::cin >> number1;
            if( number1 < 0)
            {
                throw 1;
            }
            else
                keep_going = false;
            
            std::cout << "2nd number: ";
            std::cin >> number2;
            if( number2 < 0)
            {
                throw 2;
            }
            else
                keep_going = false;
        }
        
        catch(int e)
        {
            keep_going = true;
            std::cout << "Error no: " << e << '\n';
        }
    }
    
    std::cout << "The 2 numbers are " << number1 << ' ' << number2 << '\n';
    return 0;
}
I used int as the return type because the exercise said so. Otherwise I really would've used a double.

I'm checking for negative inputs and results because I don't want to include negative numbers. Is that not a good idea?
These are the requirements:

"Using a for loop, write code that will compute the result of an int raised to the power of another int. For example, your for loop should use two variables, one for the base and one for the exponent. It should then calculate the base raised to the exponent. 2 raised to the power of 2 should output 4, 2 raised to 8 should output 256, etc. Ensure your code meets these requirements and then paste it in the response section below:"

"Contains a variable for the base
Contains a variable for the exponent
Uses a for loop to perform the power function
Outputs the result to the console window"


Nowhere under what you've posted as 'requirements' does it state say it should return int and it would be meaningless to return int as int^int could v easliy go beyond max limit int. Similary the 'requirements' does not state anything about negative numbers, these are just your interpretations or you've not posted all the requirements
closed account (48T7M4Gy)
I agree, I think the negative number thing is a red herring. So by excluding them via a try catch system if you have to saves a lot of unnecessary bother. Also, there's no harm in asking your teacher for clarification.
I'm checking for negative inputs and results because I don't want to include negative numbers. Is that not a good idea?

Why not exclude odd numbers instead? The requirements that you've posted don't mention any odd numbers so why not exclude them?

Obviously that's nonsense, but think about it: why does it seem okay to exclude negative numbers, and not okay to exclude odd ones? The real answer is "because writing the code to handle negative numbers is harder." In the real world, this can be a very costly mistake, so it's important to nail down the exact requirements.

In this case, the requirements that you've posted specifically say "an int to the power of another int." Type int includes negative numbers, so excluding them makes about as much sense as excluding odd numbers.

However, this does assume that the professor was being deliberate when saying "int" instead of "unsigned int", and the fact that he/she didn't give an example with a negative number indicates that he might have been careless. So I'd definitely ask for some clarification on whether the base and/or exponent can be negative? Also, you should ask if he/she cares what the program does in the case of an overflow. Merely asking this question will get you some brownie points because it shows that you're carefully thinking through all the possible inputs.
Topic archived. No new replies allowed.