In: Computer Science
Each new term in the Fibonacci sequence is generated by adding
the previous two terms. By starting with 1 and 2, the first 10
terms will be:
1,2,3,5,8,13,21,34,55,89,...
By considering the terms in the Fibonacci sequence whose values do
not exceed 1000, find the sum of
the all the terms up to 300.
Fibonacci Sequence:
A series of numbers in which each number is the sum of the two preceding numbers. The actual sequence of numbers will starts from 0 and the second number is 1. But 0+1 is equal to 1, we will not consider the value of 0 in the fibonacci sequence.
According to the given question, we have to find out the fibonacci sequence of numbers upto 300. And we have to add the obtained numbers. Below i am providing the C program according to the given conditions in the question.
Raw Code for the given problem:
#include<stdio.h>
int main()
{
/*these are the variables we use to write the code.
i is to get the fibonacci series and sum of that series using for
loop.
n is the number which is used to calculate according to our
requirement.
t1 is the starting initialization of the series.
t2 is the next number to be added to obtain the fibonacci
series.
nextTerm variable is to find the next term of the series.
*/
int i,n,t1=0,t2=1,nextTerm;
//sum variable is initialized to 0 at first and used to calcute the
sum of the fibonacci sequence obtained
int sum=0;
//Asking for the user input for the range that we want
printf("Enter the value for n:");
//Scaning the input that we give to the system.
scanf("%d",&n);
//using for loop for the fibonacci sequence
for(i=1;t1<=n;i++)
{
//Printing the fibonacci numbers
upto required range
printf("%d\n",t1);
//nextTerm is obtained by adding
two of its preceeding numbers
nextTerm = t1 + t2;
//Below is the logic to get
fibonacci sequence
t1 = t2;
t2 = nextTerm;
//To get the sum of the fibonacci
sequence that we obtained.
sum=sum+t1;
}
//Printing the fibonacci sequence sum.
printf("The sum of the fibonacci series less than 300
is:%d",sum);
}
Source Code for given problem:
Out put of the above code:
I have explained the entired code using comments in the program. With those the code will understand easily.
Hope the above is helpful. Please feel free to comment if any queries in the
comment section. I will try to solve them as soon as possible.
Do an up vote. Thank you..