Fibonacci Series
Solution using C language:
- #include<stdio.h>
- int main(){
- int i,range;
- long int arr[40];
- printf("Enter the number range: ");
- scanf("%d",&range);
- arr[0]=0;
- arr[1]=1;
- for(i=2;i<range;i++){
- arr[i] = arr[i-1] + arr[i-2];
- }
- printf("Fibonacci series is: ");
- for(i=0;i<range;i++)
- printf("%ld ",arr[i]);
- return 0;
- }
- Output:
Enter the number range: 20 Fibonacci series is: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181Alternate Solution using While loop in c:- #include<stdio.h>
- int main(){
- int k=2,r;
- long int i=0l,j=1,f;
- printf("Enter the number range:");
- scanf("%d",&r);
- printf("Fibonacci series is: %ld %ld",i,j);
- while(k<r){
- f=i+j;
- i=j;
- j=f;
- printf(" %ld",j);
- k++;
- }
- return 0;
- }
- Output:
Enter the number range: 10 Fibonacci series is: 0 1 1 2 3 5 8 13 21 34
- Alternate Solution using recursion in c:
- #include <stdio.h>
- #include <conio.h>
- unsigned long fib(int);
- void main()
- {
- int n,i;
- unsigned long f;
- clrscr();
- printf("\nENTER A NUMBER: ");
- scanf("%d",&n);
- printf("\nTHE FIBONNACI SERIES UPTO %d NUMBERS IS:\n",n);
- for(i=0;i<n;i++)
- {
- f=fib(i);
- printf("%lu ",f);
- }
- getch();
- }
- unsigned long fib(int x)
- {
- unsigned long res;
- if(x==0)
- return(0);
- else
- if(x==1)
- return(1);
- else
- {
- res=fib(x-1)+fib(x-2);
- return(res);
- }
- }
- Output:
ENTER A NUMBER: 10 THE FIBONNACI SERIES UPTO 10 NUMBERS IS 0 1 1 2 3 5 8 13 21 34
No comments:
Post a Comment