C Program to display the Fibonacci Series up-to a certain number - wordsclank.in

Saturday 3 March 2018

C Program to display the Fibonacci Series up-to a certain number

Before we start coding lets know what exactly Fibonacci Sequence is?
A series of a number in which each number is sum of the two preceding numbers.
For example,  1,1,2,3,5,8,13,.. is the simplest fibonacci series.

wordsclank.blogspot.com
Most related






SOURCE CODE

>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<stdio.h>
void main()
{
 int i, n, a=0, b=1, nxt;
 
 printf("Enter the number:\n");
 scanf("%d",&amp;n);
 
 printf("The Fibonacci series is: 1, \t ");
 // first two term will always 1
 
 nxt = a + b;
 
 while(nxt &lt;= n)
 {
  printf("%d, \t",nxt);
  a = b;
  b = nxt;
  nxt = a + b;
 }
 
}

OUTPUT

Words Clank,wordsclank

Explanation

Within the main() function first we declarer i, n, a=0, b=1, nxt  as integer variable.Next we display a message for the user to give input.Then we store the value given by the user in n.Then again we display a message that  "The Fibonacci series is: 1, ".Here we have already printed the first term as 1 because we know that the first term of a Fibonacci series is always 1.Then in nxt we store the value of a+b.Then  we are running a  while loop that will run until nxt less then equall to number n.Within the loop first we are printing the value of nxt then we are assigning the value of a to b and then we are assigning the value of nxt to b and then again we are assigning the value of nxt as a+b.

Related Topics

No comments:

Post a Comment