C Program to Print a Fibonacci Series Pyramid

1. Introduction

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. In this blog post, we're going to write a C program that prints a pyramid using the Fibonacci series. This program not only illustrates how to generate Fibonacci numbers but also how to display them in a pyramid pattern, demonstrating an interesting way to combine numerical patterns with geometric shapes.

2. Program Steps

1. Define the number of rows for the pyramid.

2. Generate the Fibonacci series up to the required number of elements.

3. Print the Fibonacci numbers in a pyramid shape, aligning the numbers in each row centered.

3. Code Program

#include <stdio.h>

void printFibonacci(int n) {
    int a = 0, b = 1, c, i, j, k = 0;
    for(i = 1; i <= n; ++i) {
        // Printing leading spaces for pyramid shape
        for(j = 1; j <= n - i; ++j) {
            printf("  ");
        }
        for(j = 1; j <= i; ++j) {
            if(k <= 1) {
                c = k++;
            } else {
                c = a + b;
                a = b;
                b = c;
            }
            printf("%d ", c);
        }
        printf("\n");
    }
}

int main() {
    int n;

    // Asking for user input
    printf("Enter the number of rows: ");
    scanf("%d", &n);

    printFibonacci(n);

    return 0;
}

Output:

Enter the number of rows: 5
        0
      1 1
    1 2 3
  3 5 8 13
21 34 55 89 144

Explanation:

1. The program starts by including the stdio.h header file for input and output functions.

2. A function printFibonacci is defined to generate and print Fibonacci numbers in a pyramid pattern. It takes an integer n, representing the number of rows in the pyramid.

3. Inside printFibonacci, integers a, b, and c are initialized for generating Fibonacci numbers, with a and b starting the series at 0 and 1, respectively.

4. The outer for loop (i) iterates over each row, while the first inner loop (j) prints the leading spaces needed to form the pyramid shape.

5. The second inner loop (j) generates and prints the Fibonacci numbers. The variable k is used to handle the first two numbers of the series, and thereafter, c is calculated as the sum of a and b. The values of a and b are updated accordingly.

6. The main function prompts the user to enter the number of rows for the pyramid and calls printFibonacci to generate and print the pyramid.

7. After executing printFibonacci, the program ends with return 0;, signaling successful completion.


Comments