Function randomly loops

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Jan 2009
Posts: 1
Reputation: phoniel is an unknown quantity at this point 
Solved Threads: 0
phoniel phoniel is offline Offline
Newbie Poster

Function randomly loops

 
0
  #1
Jan 18th, 2009
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:

  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?
Reply With Quote Quick reply to this message  
Join Date: Sep 2008
Posts: 146
Reputation: devnar will become famous soon enough devnar will become famous soon enough 
Solved Threads: 16
devnar's Avatar
devnar devnar is offline Offline
Junior Poster

Re: Function randomly loops

 
1
  #2
Jan 18th, 2009
The if statement is wrong. It should be:

  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.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the C++ Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC