A Fibonacci sequence is defined as follows: the first and second terms in the sequence are 0 and 1. Subsequent terms are found by adding the preceding two terms in the sequence. Write a C program to generate the first n terms of the sequence.
A Fibonacci sequence is defined as follows: the first and second terms in the sequence are 0 and 1. Subsequent terms are found by adding the preceding two terms in the sequence. Write a C program to generate the first n terms of the sequence.
Algorithm
start
step1: a := 0, b:= 1
step2: Read n
step3: Print "Fibonacci sequence" a,b
step4: for i := 3 to n step 1 do
step5: next := a + b
step6: Print next
step7: a := b
step8: b := next
stop
Flowchart
C Programming
//to generate the first n terms of the Fibonacci sequence
#include <stdio.h>
int main() {
int n, a = 0, b = 1, next,i;
printf("Enter the number of terms you want in the Fibonacci sequence: ");
scanf("%d", &n);
printf("Fibonacci Sequence:\n");
printf("%d %d ",a,b);
for (i = 3; i <= n; i++) {
next = a + b;
printf("%d ", next);
a = b;
b = next;
}
return 0;
}
OUTPUT
Enter the number of terms you want in the Fibonacci sequence: 9
Fibonacci Sequence:
0 1 1 2 3 5 8 13 21
๐ป Run This C Program
A Fibonacci sequence is defined as follows: the first and second terms in the sequence are 0 and 1. Subsequent terms are found by adding the preceding two terms in the sequence. Write a C program to generate the first n terms of the sequence.
The selected C program is loaded automatically. Edit the code,
provide input through STDIN and click Run.
The compiler is embedded using OneCompiler. Your program runs in
the embedded C environment; Study Glance does not execute C code
directly on your web server.