C Online Compiler
Example: Fibonacci Series - Iterative Function in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Fibonacci Series - Iterative Function #include <stdio.h> // Function to print the Fibonacci series up to 'n' terms iteratively void printFibonacciIterative(int n) { // Step 1: Initialize the first two Fibonacci numbers int first = 0; int second = 1; int next; printf("Fibonacci Series (Iterative) up to %d terms: ", n); // Step 2: Handle edge cases for n=0 or n=1 if (n <= 0) { printf("No terms to display.\n"); return; } else if (n == 1) { printf("%d\n", first); return; } // Step 3: Print the first two terms printf("%d, %d", first, second); // Step 4: Loop from the 3rd term up to n terms for (int i = 3; i <= n; i++) { next = first + second; printf(", %d", next); first = second; // Move 'second' to 'first' second = next; // Move 'next' to 'second' } printf("\n"); } int main() { int numTerms; // Step 1: Prompt user for the number of terms printf("Enter the number of terms for Fibonacci Series: "); scanf("%d", &numTerms); // Step 2: Call the function to print the series printFibonacciIterative(numTerms); return 0; }
Output
Clear
ADVERTISEMENTS