Reputation: 680
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;
}
Upvotes: 4
Views: 72
Reputation: 3311
use this
#include<stdio.h>
int fn(int n) {
if (n == 1 || n == 0)
return 1;
return fn(n - 1) + fn(n - 2);
}
int main()
{
int n, k = 1;
scanf("%d",&n);
k = fn(n);
printf("%d", k);
return 1;
}
Here is a little modification
if (n == 1 || n == 0)
Upvotes: 1
Reputation: 12272
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;
Upvotes: 4
Reputation: 3480
Your may enter an infinite recursion if n is lower than 3. You need to change your condition to check if n<3 return 1
Upvotes: 2