Write a C, C++ program to print sum of Fibonacci Series. Given a positive integer n, print the sum of Fibonacci Series upto n term.
Let's first brush up the concept of Fibonacci series.
In Fibonacci series, the first two numbers are 0 and 1 , and the remaining numbers are the sum of previous two numbers.
Let's take another example, this time n is 8 ( n = 4). Then the output is 33 ( 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13).
Print Fibonacci series using iterative approach
Print Fibonacci series using recursion
Output :
Enter the range : 8
Sum of Fibonacci series for given range is : 33
C, C++ Interview Questions
Programming questions on Strings
Let's first brush up the concept of Fibonacci series.
Fibonacci series
In Fibonacci series, the first two numbers are 0 and 1 , and the remaining numbers are the sum of previous two numbers.
Suppose, if input number is 4 then it's Fibonacci series is 0, 1, 1, 2. Now, we are finding sum of Fibonacci series so the output is 4 ( 0 + 1 + 1 + 2).
Let's take another example, this time n is 8 ( n = 4). Then the output is 33 ( 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13).
Print Fibonacci series using iterative approach
Print Fibonacci series using recursion
Program to Find Sum of Fibonacci Series - C Code
#include <stdio.h> int main(void) { int i, n, first = 0, second = 1, sum = 1, third; printf (" Enter the range \n"); scanf( "%d", &n); for(i = 2; i < n; i++){ /* Sum of previous two element */ third = first + second; sum = sum + third; first = second; second = third; } printf("Sum of Fibonacci series for given range is %d", sum); return 0; }
Find Sum of Fibonacci Series - C++ Code
#include <iostream> using namespace std; int main() { int i, n, first = 0, second = 1, sum = 1, third; cout << " Enter the range \n"; cin >> n; for(i = 2; i < n; i++){ /* Print the sum of previous two element */ third = first + second; sum = sum + third; first = second; second = third; } cout << "Sum of Fibonacci series for given range is " << sum; return 0; }
Output :
Enter the range : 8
Sum of Fibonacci series for given range is : 33
C, C++ Interview Questions
Programming questions on Strings
No comments:
Post a Comment