w3resource

C Exercises: Print the Floyd's Triangle


22. Floyd's Triangle

Write a program in C to print Floyd's Triangle.
The Floyd's triangle is as below :

1 
01 
101
0101
10101

This C program prints Floyd's Triangle, a triangular array of binary numbers (0s and 1s). The program prompts the user for the number of rows and then generates the triangle by alternating between 0s and 1s in a specific pattern. The resulting triangle is printed row by row, creating a visually distinct pattern with each row having an increasing number of elements.

Visual Presentation:

Print the Floyd's Triangle

Sample Solution:

C Code:

#include <stdio.h> // Include the standard input/output header file.

void main()
{
    int i, j, n, p, q; // Declare variables to store input and control loop indices.

    printf("Input number of rows : "); // Prompt the user for input.
    scanf("%d", &n); // Read the value of 'n' from the user.

    for (i = 1; i <= n; i++) // Loop for the number of rows.
    {
        if (i % 2 == 0) // Check if 'i' is even.
        {
            p = 1;
            q = 0;
        }
        else // If 'i' is odd.
        {
            p = 0;
            q = 1;
        }

        for (j = 1; j <= i; j++) // Loop for each element in the row.
        {
            if (j % 2 == 0) // Check if 'j' is even.
                printf("%d", p); // Print 'p' if 'j' is even.
            else
                printf("%d", q); // Print 'q' if 'j' is odd.
        }

        printf("\n"); // Move to the next line after printing a row.
    }
}

Output:

Input number of rows : 5                                                                                      
1                                                                                                             
01                                                                                                            
101                                                                                                           
0101                                                                                                          
10101

Flowchart:

Flowchart: Print the Floyd's Triangle

For more Practice: Solve these Related Problems:

  • Write a C program to print Floyd's Triangle and then reverse the order of numbers in each row.
  • Write a C program to display Floyd's Triangle with alternating row alignments (left and right).
  • Write a C program to print Floyd's Triangle and calculate the sum of each row.
  • Write a C program to generate Floyd's Triangle recursively.

Go to:


PREV : Sum of Series [9 + 99 + 999 + …].
NEXT : Sum of Series [ 1+x+x^2/2!+x^3/3!+....].

C Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.