You are on page 1of 3

iterative algorithm fibonacci c++

1. /*
2. * C++ Program to Find Fibonacci Numbers using Iteration
3. */
4. #include <cstring>
5. #include <iostream>
6. #include <cstdlib>
7. #define ll long long
8. using namespace std;
9.
10. /*
11. * Iterative function to find Fibonacci Numbers
12. */
13. ll fibo_iter(int n)
14. {
15. int previous = 1;
16. int current = 1;
17. int next = 1;
18. for (int i = 3; i <= n; ++i)
19. {
20. next = current + previous;
21. previous = current;
22. current = next;
23. }
24. return next;
25. }
26. /*
27. * Main
28. */
29. int main()
30. {
31. int n;
32. while (1)
33. {
34. cout<<"Enter the integer n to find nth fibonnaci no.(0 to exit): ";
35. cin>>n;
36. if (n == 0)
37. break;
38. cout<<fibo_iter(n)<<endl;
39. }
40. return 0;
41. }
Recursive algorithm fibonacci

42. /*
43. * C++ Program to Find Fibonacci Numbers using Recursion
44. */
45. #include <cstring>
46. #include <iostream>
47. #include <cstdlib>
48. #define ll long long
49. using namespace std;
50.
51. /*
52. * Recursive function to find Fibonnaci Numbers
53. */
54. ll fibo_recur(int n)
55. {
56. if (n == 1 || n == 2)
57. return 1;
58. else
59. return fibo_recur(n - 1) + fibo_recur(n - 2);;
60. }
61. /*
62. * Main
63. */
64. int main()
65. {
66. int n;
67. while (1)
68. {
69. cout<<"Enter the integer n to find nth fibonnaci no.(0 to exit): ";
70. cin>>n;
71. if (n == 0)
72. break;
73. cout<<fibo_recur(n)<<endl;
74. }
75. return 0;
76. }

Algorithm to find the n-th number

77. /*
78. * C Program to find the nth number in Fibonacci series using recursion
79. */
80. #include <stdio.h>
81. int fibo(int);
82.
83. int main()
84. {
85. int num;
86. int result;
87.
88. printf("Enter the nth number in fibonacci series: ");
89. scanf("%d", &num);
90. if (num < 0)
91. {
92. printf("Fibonacci of negative number is not possible.\n");
93. }
94. else
95. {
96. result = fibo(num);
97. printf("The %d number in fibonacci series is %d\n", num, result);
98. }
99. return 0;
100. }
101. int fibo(int num)
102. {
103. if (num == 0)
104. {
105. return 0;
106. }
107. else if (num == 1)
108. {
109. return 1;
110. }
111. else
112. {
113. return(fibo(num - 1) + fibo(num - 2));
114. }
115. }