#include <stdio.h>
int main() {
int n, firstTerm = 0, secondTerm = 1, nextTerm;
// Asking the user for the number of terms
printf("Enter the number of terms: ");
// Input validation for non-negative integers
if (scanf("%d", &n) != 1 || n < 0) {
printf("Invalid input. Please enter a non-negative integer.\n");
return 1; // Returning 1 indicates abnormal termination
}
// Edge cases for Fibonacci sequence
if (n == 0) {
printf("Fibonacci series: No terms to display.\n");
} else if (n == 1) {
printf("Fibonacci series: %d\n", firstTerm);
} else {
// Printing the first two terms
printf("Fibonacci series: %d, %d", firstTerm, secondTerm);
// Loop to calculate the next terms
for (int i = 3; i <= n; ++i) {
nextTerm = firstTerm + secondTerm; // The next term is the sum of the previous two terms
printf(", %d", nextTerm); // Printing the next term
firstTerm = secondTerm; // Update firstTerm to the next term
secondTerm = nextTerm; // Update secondTerm to the next term
}
printf("\n"); // Newline for output formatting
}
return 0; // Returning 0 indicates successful termination
}
Explanation:
- Including the standard input-output library: We include
stdio.hto use functions likeprintfandscanffor input and output.cCopy code#include <stdio.h> - Main function: Program execution begins from the
main()function.cCopy codeint main() { ... } - Declaring variables:
nstores the number of terms the user wants to print in the Fibonacci series.t1is initialized to0, which represents the first term in the Fibonacci series.t2is initialized to1, which represents the second term in the Fibonacci series.nextTermwill store the next number in the sequence as we compute it.
int n, t1 = 0, t2 = 1, nextTerm; - User input: We prompt the user to input the number of terms using
printfand then usescanfto store this value in the variablen.cCopy codeprintf("Enter the number of terms: "); scanf("%d", &n); - Printing the Fibonacci series:
- We use a
forloop that runsntimes, which means it will print the firstnterms of the Fibonacci series. - Inside the loop:
- We print
t1, which is the current term in the series. - We then calculate the next term in the Fibonacci series by adding
t1andt2. - After calculating
nextTerm, we updatet1tot2andt2tonextTermto move the sequence forward.
- We print
- This process is repeated until we print the required number of terms.
for (int i = 1; i <= n; ++i) { printf("%d ", t1); nextTerm = t1 + t2; t1 = t2; t2 = nextTerm; } - We use a
- Returning 0: The program returns
0to indicate that it has executed successfully.cCopy code
OUTPUT
Enter the number of terms: 10
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34
Summary:
It uses a simple loop and updates the terms of the series iteratively.
The Fibonacci series is a sequence where each number is the sum of the two preceding ones, starting with 0 and 1.
The program prints the Fibonacci series up to the number of terms specified by the user.