The 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. The sequence looks like this:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Logic to Generate Fibonacci Series:
- Start with the first two numbers in the Fibonacci series, typically 0 and 1.
- For the next number, sum the two preceding numbers.
- Repeat the process for the desired count of numbers in the series.
Program:
Here’s a simple C program to print the Fibonacci series up to a specified number of terms:
Explanation:
Variables:
int n
: This variable holds the number of terms in the Fibonacci series that the user wants to print.int i
: This is a loop counter.int t1
: This variable holds the first term in the series (initialized to 0).int t2
: This variable holds the second term in the series (initialized to 1).int nextTerm
: This variable is used to calculate the next term in the series.
Input:
- The program prompts the user to enter the number of terms (
n
) they want in the Fibonacci series.
- The program prompts the user to enter the number of terms (
Fibonacci Calculation:
- A
for
loop runs from 1 ton
to generate the Fibonacci series. - First and Second Terms: The program prints the first two terms (0 and 1) separately.
- Calculating Next Terms:
- For subsequent terms, the program calculates the next term as the sum of the previous two terms:
nextTerm = t1 + t2
. - It then updates
t1
andt2
to move to the next pair in the series. - The program prints each
nextTerm
.
- For subsequent terms, the program calculates the next term as the sum of the previous two terms:
- A
Output:
- The Fibonacci series is printed in a comma-separated format.
Sample Output:
Example 1:
Example 2:
Key Points:
- Iterative Approach: This program uses a simple iterative approach to generate the Fibonacci series.
- Variable Updates: The use of
t1
andt2
helps keep track of the last two terms, making it easy to compute the next term. - Basic Concepts: This program demonstrates basic programming concepts such as loops, conditionals, and input/output in C.