Making recursive functions work flawlessly

Asked By 10 points N/A Posted on -
qa-featured

In writing a program, how do you prevent a recursive function from running endlessly?

SHARE
Answered By 0 points N/A #95214

Making recursive functions work flawlessly

qa-featured

If you have tried with recursion, then you must be aware that the entire fact lies with calling a function with values of parameters changed. If the function is called repeatedly ,the you will see a stack overflow message. This may sometimes hang your system. The next thing you must have realised is that there is a "return" statement that exits from an instance of the function whenever a certain criteria is reached. So at last you can print 10, 9, 8, 7,….1, without using a loop in this way.

void main( ){

loop ( 1 ) ;

}

void loop ( int i ){

if ( i < 11 )

     loop ( i + 1 );

else

      return ;

print ( " % d , " , i  );

}

the condition ( i < 11 ) restricts the recursion procedure from running endlessly. When i reaches 11 ,the instance of function returns and the previous instance executes the next instruction after the loop call which is print. So it prints 10 then exits the function instance. Then the previous instance to this instance shall print 9 then 8 then 7 and so on till the first loop function call that is 1.

OUTPUT:

10, 9, 8, 7, 6, 5, 4, 3, 2, 1,

Related Questions