C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Loop Programs in C

Print Floyd’s triangle (1, 2, 3...)

Introduction

Floyd’s Triangle is a right-angled triangular array of natural numbers.
It starts with 1 and continues to fill rows with consecutive numbers.

For example, for n = 5, the pattern looks like this:

2 3 

4 5 6 

7 8 9 10 

11 12 13 14 15

This program demonstrates the use of nested loops and incremental number printing in C.

 

C Program: Print Floyd’s triangle (1, 2, 3...)

Method 1: Using for loop

C

#include <stdio.h>

 

int main() {

    int n, i, j, num = 1;

 

    printf("Enter number of rows: ");

    scanf("%d", &n);

 

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

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

            printf("%d ", num);

            num++;

        }

        printf("\n");

    }

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter number of rows: 5
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15

Explanation

  1. The user enters the number of rows (n).
  2. The outer loop controls the number of rows.
  3. The inner loop prints increasing numbers in each row.
  4. num starts at 1 and increments after every print.

 

C Program: Print Floyd’s triangle (1, 2, 3...)

Method 2: Using while loop

C

#include <stdio.h>

 

int main() {

    int n, i = 1, j, num = 1;

 

    printf("Enter number of rows: ");

    scanf("%d", &n);

 

    while (i <= n) {

        j = 1;

        while (j <= i) {

            printf("%d ", num);

            num++;

            j++;

        }

        printf("\n");

        i++;

    }

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter number of rows: 5
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15

Explanation

  1. The user enters the number of rows (n).
  2. The outer loop controls the number of rows.
  3. The inner loop prints increasing numbers in each row.
  4. num starts at 1 and increments after every print.

 

C Program: Print Floyd’s triangle (1, 2, 3...)

Method 3: Using do..while loop

C

#include <stdio.h>

 

int main() {

    int n, i = 1, j, num = 1;

 

    printf("Enter number of rows: ");

    scanf("%d", &n);

 

    do {

        j = 1;

        do {

            printf("%d ", num);

            num++;

            j++;

        } while (j <= i);

 

        printf("\n");

        i++;

    } while (i <= n);

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter number of rows: 5
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15


Explanation

  1. The user enters the number of rows (n).
  2. The outer loop controls the number of rows.
  3. The inner loop prints increasing numbers in each row.
  4. num starts at 1 and increments after every print.