Write a c program to generate fibonacci triangle.

Ram Pothuraju

 #include <stdio.h>


int main()

{

    int n, prev1 = 0, prev2 = 1;


    // Read number of rows from user

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

    scanf("%d", &n);


    // Generate Fibonacci triangle

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

    {

        int current = 1;

        

        // Print spaces before numbers

        for (int j = 1; j <= n - i; j++)

        {

            printf(" ");

        }


        // Print Fibonacci numbers

        for (int j = 1; j <= i; j++)

        {

            printf("%d ", current);

            current = prev1 + prev2;

            prev1 = prev2;

            prev2 = current;

        }


        printf("\n");

    }


    return 0;

}



In this program, we first read the number of rows for the triangle from the user using the scanf() function.

We then use nested loops to generate each row of the triangle. For each row, we first print the necessary spaces before the numbers to center the triangle. We then print the Fibonacci numbers up to the current row, and then move to the next line using the printf() function.

Note that this program assumes that the number of rows entered by the user is positive. You may want to add input validation to ensure that the input is valid. Also, note that the Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the previous two numbers.




Tags

Post a Comment

0Comments

Post a Comment (0)