This blog is under construction

Sunday, 23 June 2013

C program to generate Fibonacci series

What is Fibonacci Number?
Fibonacci numbers are the numbers in the following sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ..
0 and 1 are the first two Fibonacci numbers in the sequence and the subsequent numbers are the sum of previous two.


Write a C program to find first N Fibonacci numbers.


  #include <stdio.h>
  int main() {
        int n, num1 = 0, num2 = 1, i = 2, temp;
        printf("Enter the value for n:");
        scanf("%d", &n);
        if (n <= 0) {
                printf("Wrong input!!!\n");
        } else if (n == 1) {
                printf("%d\n", num1);
        } else {
                printf("%d %d ", num1, num2);
                while (i < n) {
                        temp = num2;
                        num2 = num2 + num1;
                        num1 = temp;
                        printf("%d ", num2);
                        i++;
                }
        }
        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:10
  0 1 1 2 3 5 8 13 21 34 



No comments:

Post a Comment