📌  相关文章
📜  c program for fibonacci series - C 编程语言(1)

📅  最后修改于: 2023-12-03 15:29:43.290000             🧑  作者: Mango

C Program for Fibonacci Series

Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. In this article, we present a C program for Fibonacci series.

The Code
#include <stdio.h>

int main()
{
   int n, t1 = 0, t2 = 1, nextTerm = 0;

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

   printf("Fibonacci Series: ");

   for (int i = 1; i <= n; ++i)
   {
       // Prints the first two terms.
       if(i == 1)
       {
           printf("%d, ", t1);
           continue;
       }
       if(i == 2)
       {
           printf("%d, ", t2);
           continue;
       }
       // Calculates the next term.
       nextTerm = t1 + t2;
       t1 = t2;
       t2 = nextTerm;

       printf("%d, ", nextTerm);
   }
   return 0;
}
Explanation of the Code

The above code is a C program for Fibonacci series. Here is how it works:

  1. The program prompts the user to enter the number of terms in the Fibonacci series.
  2. The program then prints the Fibonacci series using a for loop.
  3. Inside the for loop, the program prints the first two terms of the series (0 and 1) and then calculates and prints the subsequent terms using the formula nextTerm = t1 + t2.
  4. The loop continues until the desired number of terms is printed.
Conclusion

In this article, we presented a C program for Fibonacci series. This code can be used to print any number of terms in the Fibonacci series.