Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call recursion in different way?

Tags:

c

recursion

When I run this code, I got an exception like

Unhandled exception at 0x779C017E (ntdll.dll) in ConsoleApplication1.exe: 0x00000000: The operation completed successfully.

If there is a handler for this exception, the program may be safely continued.

How do i fixed it ?? And thanks in advance.

#include<stdio.h>

int fn(int n) {
if (n == 1)
  return 1;
  return fn(n - 1) + fn(n - 2);
}

int main()
{
 int n, k = 1;
 scanf_s("%d",&n);
 k = fn(n);
 printf("%d", k);
 return 1;

}
like image 865
Joy Acharya Avatar asked Mar 14 '23 23:03

Joy Acharya


1 Answers

Your code has condition which will always lead to an infinite loop(Not just for 3).

Consider entering 5 as input. 5 would break into 4 and 3. 3 would break into 2 and 1. 2 would break into 1 and 0. Now the function which gets the 0 value will go into infinite recursion.

This way, whatever value you input, the value will break down to 0 and eventually would lead to infinite recursion. This should be handled in the condition check.

Your condition check should be

if (n <= 1)
   return 1;
like image 197
Haris Avatar answered Mar 29 '23 16:03

Haris