The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. The series is represented as 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. In other words, each number in the series (after the first two numbers) is the sum of the two preceding ones.
In this article, we are going to print the Fibonacci series using C programming.
Algorithm to Print Fibonacci Series.
- Input the number of terms 'n' from the user.
- Initialize variables 'first' and 'second' as 0 and 1, respectively, representing the first two numbers of the series.
- Print the first two numbers of the series, i.e., 0 and 1.
- Use a loop to calculate and print the subsequent terms of the series.
- In each iteration, calculate the next term as the sum of the 'first' and 'second'.
- Update 'first' to the value of 'second' and 'second' to the value of the newly calculated term.
- Repeat steps 4 to 6 'n-2' times, as the first two numbers are already printed.
Below is the C program to display Fibonacci Series.
//c program for fibonacci sequqence. #include <stdio.h> int main() { int n, first = 0, second = 1, next; printf("Enter the number of terms in the Fibonacci series: "); scanf("%d", &n); printf("Fibonacci Series: "); // Print the first two terms printf("%d, %d", first, second); // Calculate and print the subsequent terms for (int i = 2; i < n; i++) { next = first + second; printf(", %d", next); // Update first and second for the next iteration first = second; second = next; } printf("\n"); return 0; }
Enter the number of terms in the Fibonacci series: 7
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8
Time Complexity: The time complexity of the given C program to print the Fibonacci series is O(n), where 'n' is the number of terms in the series.
Space Complexity: The space complexity of the program is O(1), which means it uses constant space.
No comments:
Post a Comment