Find the terms of Fibonacci sequence in C-Programming (Using For-loop):
First of all we have to know what is Fibonacci Sequence. So Fibonacci sequence starts with two initial value 0 and 1. After that the next term of the sequence will be addition of 0 and 1 that is 1.Now we have three terms of the sequence they are 0,1,1 now next term will be addition of previous two terms that is 1 and 1 so 4th term of the sequence would be 2 and so on. Generally the Fibonacci sequence is like {0,1,1,2,3,5,8,13,21,35,...}. Now we will do it on C-Program.Code:
#include<stdio.h>
int main()
{
int n,f=0,s=1,sum,i;
printf("How many term you want to see:");
scanf("%d",&n);
printf("The first %d terms are\n",n);
for(i=0;i<n;i++)
{
printf("%d\n",f);
sum=f+s;
f=s;
s=sum;
}
}
Output:
The output is given below:
Explanation:
1. We use the Header package <stdio.h>.2. Next we introduce 5 integers variables n,f,s,sum and i. Now we use 'n' for save the value that how many terms the users want to find. Next we use 'f' and 's' for the initializing. Since Fibonacci sequence is starting with 0 and 1 so we save the initial value of 'f' is 0 and 's' is 1. We use 'sum' to add the numbers and 'i' for loop.
3. We use for-loop here. First we introduce the condition i starts from 0 and increasing by 1 it will stop at 'n'(users input this number).
4. Every time in for loop first print the value of f then it will do the sum=f+s then we save 'f' in 's' and after that save 's' in the variable 'sum'. So what is happened here, first it will print 0 since 0 is the initial value of 'f', then sum=0+1=1 after that f=1 since the initial value of 's' is 1. After that s=1 since 'sum' has the value 1. Again loop is begin and print the value of 'f' i.e 1 here and continue in this way.
No comments:
Post a Comment