Cover Image for Fibonacci Triangle in C++
109 views

Fibonacci Triangle in C++

A Fibonacci triangle in C++ is a pattern of numbers where each number in a row is the sum of the two numbers directly above it in the previous row, similar to the Fibonacci sequence. Here’s how you can create a Fibonacci triangle in C++:

C++
#include <iostream>

int main() {
    int n;

    // Input the number of rows for the Fibonacci triangle
    std::cout << "Enter the number of rows: ";
    std::cin >> n;

    int a = 0, b = 1, c;

    for (int i = 1; i <= n; ++i) {
        a = 0;
        b = 1;
        for (int j = 1; j <= i; ++j) {
            std::cout << a << " ";
            c = a + b;
            a = b;
            b = c;
        }
        std::cout << std::endl;
    }

    return 0;
}

In this program:

  1. The user is prompted to enter the number of rows for the Fibonacci triangle.
  2. Two variables a and b are used to keep track of the last two Fibonacci numbers, initially set to 0 and 1.
  3. Nested loops are used to iterate through the rows and columns of the triangle.
  4. In the inner loop, the current Fibonacci number (a) is printed, and the next Fibonacci number is calculated (c = a + b). Then, a is updated to b, and b is updated to c.
  5. The result is a pattern of numbers forming a Fibonacci triangle.

For example, if you enter 5 as the number of rows, the program will generate the following Fibonacci triangle:

Plaintext
0 
1 1 
1 2 3 
5 8 13 21 
34 55 89 144 233 

You can adjust the number of rows by changing the value of n to create a Fibonacci triangle of the desired size.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS