154 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:
- We ask the user to input the number of rows for the Fibonacci triangle.
- We use two variables,
a
andb
, to keep track of the last two Fibonacci numbers. We initializea
to 0 andb
to 1. - 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. - Inside the inner loop, we print the value of
a
, which is the current Fibonacci number, and then updatea
andb
to calculate the next Fibonacci number (c
) for the next iteration. - 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.