C Online Compiler
Example: Fibonacci Series (Iterative) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Fibonacci Series (Iterative) #include <stdio.h> int main() { int n, i; int t1 = 0, t2 = 1; int nextTerm; // Step 1: Prompt user for the number of terms printf("Enter the number of terms: "); scanf("%d", &n); printf("Fibonacci Series: "); // Step 2: Handle edge cases for n = 1 or n = 2 if (n <= 0) { printf("Please enter a positive integer.\n"); } else if (n == 1) { printf("%d\n", t1); } else { // Step 3: Iterate and print the series // Print the first two terms outside the loop printf("%d, %d", t1, t2); // Calculate and print subsequent terms for (i = 3; i <= n; ++i) { nextTerm = t1 + t2; printf(", %d", nextTerm); t1 = t2; t2 = nextTerm; } printf("\n"); } return 0; }
Output
Clear
ADVERTISEMENTS