943,920 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 309
  • C++ RSS
Jan 18th, 2009
0

Function randomly loops

Expand Post »
Hey - I'm new asking questions here. I'm writing a simple program to give a number to a power using a recursive function (inconvenient, but that's the assignment). It seems as though the program should work, and debugging shows that it almost does. It has the right value up until it's about to return, and then it jumps back and multiplies the value further. For the purposes of debugging, it has been modified to only take 5^3.
Take a look:

C++ Syntax (Toggle Plain Text)
  1. // Recursive Power Program
  2.  
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7. int power(int, int, int);
  8.  
  9. int main()
  10. {
  11. int num = 5, pow = 3, full;
  12. //cin >> num; - out for the purposes of debugging; the program will return 5^3
  13. //cin >> pow;
  14. full = num;
  15. cout << power(num, pow, full);
  16. char response;
  17. cin >> response;
  18. }
  19.  
  20. int power(int num, int pow, int full)
  21. {
  22. if (pow > 1)
  23. {
  24. full = num * full; //Multiplies the original number by itself, and sets the new amount to full
  25. return (num * power(num, --pow, full)); //Multiplies the original number by full again and again until pow is 1
  26. }
  27. else
  28. {
  29. cout << full; //Just to make sure full had the correct value here (it did)
  30. return full; //The problem is here. Full = 125 here, but it then jumps back up to the return in the IF statement above, multiplying it 3 more times...
  31. }
  32. }

I'm totally confused as to why this would happen. Any ideas?
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
phoniel is offline Offline
1 posts
since Jan 2009
Jan 18th, 2009
1

Re: Function randomly loops

The if statement is wrong. It should be:

cpp Syntax (Toggle Plain Text)
  1. if (pow > 1)
  2. {
  3. full = num * full;
  4. return (power(num, --pow, full)); //You've already multiplied once. Don't do it again.
  5. }

Also, your code breaks when pow = 0. Anyway, it's an easy thing to fix.
Last edited by devnar; Jan 18th, 2009 at 2:47 am.
Reputation Points: 124
Solved Threads: 18
Junior Poster
devnar is offline Offline
148 posts
since Sep 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: any suggestion?
Next Thread in C++ Forum Timeline: C++ permutations of 6 numbers. help!





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC