Fibonacci Sequence Generator in C
C Program to generate Fibonacci sequence.
C Program to generate Fibonacci sequence.
Write a program to generate the first n numbers of the Fibonacci sequence using a loop of your choice.
The Fibonacci sequence is a sequence in which each number is obtained by adding the previous two numbers. For example, if we want to know the 7th Fibonacci number in the sequence, then we need to add the 6th and the 5th Fibonacci number.
So, Fib(7) = Fib(6) + Fib(5)
In the same way, Fib(n) = Fib(n-1) + Fib(n-2)
Following are some of initial numbers in the Fibonacci sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …
Note: we are assuming that the Fibonacci sequence starts from the zeroth term.
Input:
Enter the number: 8
Output:
0, 1, 1, 2, 3, 5, 8, 13
Input:
Enter the number: 0
Output:
No output
You need to write the complete program using the following template as the starter:
#include <stdio.h>
int main()
{
int n;
printf("Enter a number: ");
scanf("%d", &n);
// Write your code here.
return 0;
}
Copy and paste the above code in your favorite IDE and start writing your code after the comment “// Write your code here.”
Pro tip: First, try writing the code on your own. Try every possible thing you can to come up with the solution. If you still can’t figure it out, then check the solution and see what went wrong. This is how you learn. 🙂
To verify the program you have written, go ahead and test your program using the following test cases:
Input | Output | |
---|---|---|
Test Case 1 | 0 | No output |
Test Case 2 | 1 | 0 |
Test Case 3 | 5 | 0, 1, 1, 2, 3 |
Test Case 4 | -10 | n cannot be negative |
Don’t forget to try the code on your own before diving into the solution.
The Fibonacci sequence generator is a famous problem in programming. Following is the solution to this problem:
#include <stdio.h>
int main()
{
int n;
printf("Enter a number: ");
scanf("%d", &n);
int first = 0, second = 1, next;
if (n < 0) {
printf("n cannot be negative.");
exit(1); // exit the program with failure
}
printf("Fibonacci Sequence: ");
if (n >= 0) printf("%d", first);
if (n >= 1) printf(", %d", second);
for (int i = 2; i < n; i++) {
next = first + second;
first = second;
second = next;
printf(", %d", next);
}
printf("\n");
return 0;
}
Let’s analyze the above program line by line:
Leave a comment