Fibonacci series

Fibonacci Series in C

To generate the Fibonacci series in C, you can use a loop to calculate each term based on the previous two terms. Here's an example code snippet that demonstrates how to generate the Fibonacci series:

#include <stdio.h>

int main() {
    int n, first = 0, second = 1, next;

    printf("Enter the number of terms: ");
    scanf("%d", &n);

    printf("Fibonacci Series: ");

    for (int i = 0; i < n; i++) {
        if (i <= 1) {
            next = i;
        } else {
            next = first + second;
            first = second;
            second = next;
        }
        printf("%d ", next);
    }

    return 0;
}

Let's go through each step of the code:

  1. We include the stdio.h header file to use the printf and scanf functions.

  2. In the main function, we declare the necessary variables:

  3. n to store the number of terms in the series.
  4. first and second to store the first two terms of the series.
  5. next to store the next term in the series.

  6. We prompt the user to enter the number of terms they want in the series using printf and scanf.

  7. We start a loop that iterates n times to calculate and print each term of the series.

  8. Inside the loop, we use an if statement to handle the first two terms of the series. If i is less than or equal to 1, we set next to i. Otherwise, we calculate next by adding first and second, and update the values of first and second accordingly.

  9. Finally, we print each term of the series using printf.

That's it! The code will generate the Fibonacci series based on the user's input.

[[SOURCE 10]]