![]() |
| ||
| Recursion in C++ HI I am trying to work on a very simple recursive function but i get o/p as some negative values.. can u please help and tell me what mistake i am doing ? #include<iostream.h> |
| ||
| Re: Recursion in C++ 1) it goes negative because there is nothing to prevent it. Its an infinit recursive function -- that is until it consumes all available stack space and then it will simply crash. You need to add a line that stops the recursion when x == 0 (or whatever other value you want). 2) replace iostream.h with <iostream>. Current c++ standards do not use the .h extension. If you compiler doesn't support <iostream> then get a newer compiler. 3) move that line using namespace std;up above just under the last include directive. It does not good to place it where it is. |
| ||
| Re: Recursion in C++ Hi AncientDragon: Thanks for ur reply.. i made some modifications.. still does not work! i get all 0s now.. #include<iostream.h> Quote:
|
| ||
| Re: Recursion in C++ you don't want a while statement, but just a simple if statement if( x > 0) |
| ||
| Re: Recursion in C++ Hey THanks it worked.. but how does it matter.. "while" was supposed to be doing the same thing..as "if" is doing now.. then why did it falter ? Quote:
|
| ||
| Re: Recursion in C++ The while didn't work because now you have recursion within recursion. Follow the function through with pencil & paper and you will see why it doesn't work like you wanted it to. |
| ||
| Re: Recursion in C++ I dont see the difference.. it is going to call the countdown function repetitively anyway..! |
| ||
| Re: Recursion in C++ With the while statement, the function will call itself billions of times. Try this version and see the results #include <iostream> |
| ||
| Re: Recursion in C++ Oh man!! Ancient Dragon would be snatching his hairs!! Look kavithabaskar, You are basically using recursions to avoid loops. Every series has Recursive form and a closed form(non-recursive)[Note that it is not possible for every series to have both forms]. Say, the series 1,2,3,4,5,6,7,8 has a recursive form as and open form as So, if you know the closed form it is best to use it through loops. But when you dont know closed form you go to recursive functions. |
| All times are GMT -4. The time now is 4:39 pm. |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC