C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Functions in C

Function for Fibonnaci Series (iteration)

C Program: Function for Fibonnaci Series (iteration)

C

#include <stdio.h>

 

// Function declaration

void fibonacci(int n);

 

int main() {

    int n;

 

    // Input number of terms

    printf("Enter the number of terms: ");

    scanf("%d", &n);

 

    // Validate input

    if (n <= 0) {

        printf("Please enter a positive integer.\n");

    } else {

        printf("Fibonacci Series up to %d terms:\n", n);

        fibonacci(n);   // Function call

    }

 

    return 0;

}

 

// Function definition

void fibonacci(int n) {

    int a = 0, b = 1, next, i;

 

    for (i = 1; i <= n; i++) {

        printf("%d ", a);

        next = a + b;

        a = b;

        b = next;

    }

    printf("\n");

}

Output

 
OUTPUT :
Enter the number of terms: 10
Fibonacci Series up to 10 terms:
0 1 1 2 3 5 8 13 21 34

Explanation

  1. Function fibonacci(int n)
    • Takes n (number of terms) as input.
    • Uses variables a and b to store the two preceding Fibonacci numbers.
    • Iteratively calculates the next term as next = a + b.
  2. No recursion — The logic runs through a for loop for efficiency.
  3. Fibonacci Logic

          0, 1, 1, 2, 3, 5, 8, 13, ...

          Each term = sum of previous two terms.