C Program to Print Floyd’s Triangle Pattern

Introduction

Floyd's Triangle is a triangular array of natural numbers, where each row contains an increasing sequence of numbers starting from 1. It is a common exercise in programming that helps you practice loops and number sequences.

Problem Statement

Create a C program that:

  • Accepts the number of rows for Floyd's Triangle.
  • Prints Floyd's Triangle with natural numbers.

Example:

  • Input: rows = 5
  • Output:
    1
    2 3
    4 5 6
    7 8 9 10
    11 12 13 14 15
    

Solution Steps

  1. Input the Number of Rows: The size determines how many rows Floyd’s Triangle will have.
  2. Use Nested Loops: The outer loop will handle the rows, while the inner loop will handle printing the numbers.
  3. Display Floyd's Triangle: Print the numbers in increasing order, row by row.

C Program

#include <stdio.h>

int main() {
    int i, j, rows, num = 1;

    // Step 1: Accept the number of rows for Floyd's Triangle
    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    // Step 2: Outer loop for the rows
    for (i = 1; i <= rows; i++) {
        // Step 3: Inner loop to print numbers
        for (j = 1; j <= i; j++) {
            printf("%d ", num);
            num++;  // Increment the number after printing
        }

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

    return 0;
}

Explanation

Step 1: Input Number of Rows

  • The program begins by asking the user to input the number of rows for Floyd’s Triangle.

Step 2: Outer Loop for Rows

  • The outer loop controls how many rows to print. It runs from 1 up to the number of rows specified by the user.

Step 3: Inner Loop for Numbers

  • The inner loop prints the numbers for each row. The number of values printed increases as the row number increases. The num variable is used to keep track of the current number to print and is incremented after each print.

Output Example

For rows = 5, the output will be:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

For rows = 6, the output will be:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21

Conclusion

This C program prints Floyd’s Triangle by incrementing and displaying numbers in increasing order row by row. The exercise is helpful in practicing nested loops and number sequences in C programming.

Comments