-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththe Fibonacci number calculator
63 lines (47 loc) · 1.27 KB
/
the Fibonacci number calculator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
Code:
/*
Humza Khawar
fibonacci series
*/
#include<stdio.h>
int Rec_fibonacci(int);//calaulates fibinocci series using recursion
int Loop_fibonacci(int);//calaulates fibinocci series using loop
int main()
{
int num;
printf("\n Enter num : ");//input number
scanf_s("%d", &num);
printf(" \nRecursion: fibonacci( %d ) is %d \n",num, Rec_fibonacci(num));//prints the desired output through recursion function
printf(" \nLoop: fibonacci( %d ) is %d \n", num, Loop_fibonacci(num));//prints the desired output through loop function
return 0;
}
int Rec_fibonacci(int num)
{
{static int first_num = 0, second_num = 1, next_num; //static variables so we can keep using their values
if (num >= 2)
{
next_num = first_num + second_num; //the fibonacci definition
first_num = second_num;
second_num = next_num;
num--;
Rec_fibonacci(num); //recursion
return next_num; //returning the result
}
else
{
return 1;
}
}
}
int Loop_fibonacci(int num)
{
int first_num = 0, second_num = 1, fib_num = 0;//initialitzation
while (num>1)//loop to sum numbers until desired number is achieved
{
fib_num = first_num + second_num;//fibonoci formula
first_num = second_num;
second_num = fib_num;
--num;
}
return fib_num;//returning value
}