Cover Image for Fibonacci Triangle in C
97 views

Fibonacci Triangle in C

A Fibonacci triangle is a triangle where each number is the sum of the two numbers directly above it, similar to the Fibonacci sequence. Here’s a C program to print a Fibonacci triangle:

C
#include <stdio.h>

int main() {
    int n, i, j;
    printf("Enter the number of rows for the Fibonacci triangle: ");
    scanf("%d", &n);

    int a = 0, b = 1, c;

    for (i = 1; i <= n; i++) {
        a = 0;
        b = 1;
        for (j = 1; j <= i; j++) {
            printf("%d ", a);
            c = a + b;
            a = b;
            b = c;
        }
        printf("\n");
    }

    return 0;
}

In this program:

  1. We ask the user to input the number of rows for the Fibonacci triangle.
  2. We use two variables, a and b, to keep track of the last two Fibonacci numbers. We initialize a to 0 and b to 1.
  3. We use two nested loops. The outer loop (i) controls the number of rows in the triangle, and the inner loop (j) prints the Fibonacci numbers for each row.
  4. Inside the inner loop, we print the value of a, which is the current Fibonacci number, and then update a and b to calculate the next Fibonacci number (c) for the next iteration.
  5. After printing all the Fibonacci numbers for a row, we move to the next row by printing a newline character (\n).

Compile and run the program, and it will display a Fibonacci triangle with the specified number of rows.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS