- Fibonacci series starts from 0 ,1 and the next number should be sum of previous two numbers.
- 0+1=1, so the next number in Fibonacci series in c program is 1. 0 1 1
- 0 1 1 2 3 5 8.. and so on.
- Now let us see and c language example program on fibonacci series.
Fibonacci series in C language:
- First print 0, 1 by default.
- and start from 2 and iterate upto n-1 using for loop.
- inside loop assign n3=n1+n2;
- and ptint sum. printf(" %d",n3);
- Assign n2 value to n1. n1=n2
- Assign sum to n2: variable n2=n3;
Program #1 : write a C program to print / generate fibonacci series up to n numbers. Take input from user without recursion
- #include <stdio.h>
- #include <stdlib.h>
- int main()
- {
- int n1=0,n2=1,n3,i,number;
- printf("Enter the number of elements to be printed in Fibonacci series:");
- scanf("%d",&number);
- printf("\n%d %d",n1,n2);//printing 0 and 1
- for(i=2;i<number;++i)//Starts from 2 to given number-1
- {
- n3=n1+n2;
- printf(" %d",n3);
- n1=n2;
- n2=n3;
- }
- getch();
- }
Output:
No comments