Use a Loop to Generate Terms
In this step, we will modify our previous Fibonacci sequence program to generate the sequence using a loop. We'll build upon the code from the previous step to create the actual Fibonacci sequence.
Let's update the fibonacci.c file:
cd ~/project
nano fibonacci.c
Now, let's modify the code to generate Fibonacci terms using a for loop:
#include <stdio.h>
int main() {
int n, first = 0, second = 1, next;
printf("Enter the number of terms in Fibonacci sequence: ");
scanf("%d", &n);
printf("Fibonacci Sequence of %d terms: \n", n);
for (int i = 0; i < n; i++) {
if (i <= 1)
next = i;
else {
next = first + second;
first = second;
second = next;
}
printf("%d ", next);
}
printf("\n");
return 0;
}
Compile and run the program:
gcc fibonacci.c -o fibonacci
./fibonacci
Example output:
Enter the number of terms in Fibonacci sequence: 10
Fibonacci Sequence of 10 terms:
0 1 1 2 3 5 8 13 21 34
Explanation
- We initialize
first and second as the first two terms of the Fibonacci sequence
- The
for loop generates subsequent terms by adding the previous two terms
next = first + second calculates the next term
- We update
first and second in each iteration to maintain the sequence progression
- The loop continues until we generate the specified number of terms