C program to print Floyd's triangle number pattern

Write a C program to print the Floyd's triangle number pattern using loop. How to print the Floyd's triangle number pattern using for loop in C programming. Logic to print the Floyd's triangle number pattern using loop in C program.

Example:
Input N: 5
Output:

Required knowledge

Basic C programming, Loop

Logic to print the Floyd's triangle number pattern

Printing the above pattern is easy if you are acquainted with basics of number pattern printing. The given pattern contains N rows (where N is the total number of rows to be printed). Each row contains exactly i columns (where i is the current row number).

Now, you have understood the looping constructs of the given pattern. As you can see that printed numbers are in increasing order, hence to print numbers we will use an extra variable k which will keep track of the next number to be printed.

Step-by-step descriptive logic:

  1. Initialize a variable k = 1 (where k is used to keep track of next number to be printed).
  2. To iterate through rows, run an outer loop from 1 to N.
  3. To print columns, run an inner loop from 1 to i (where i is the current row number).
    Inside this loop print the value of k also increment the value of k to k = k + 1.



Program to print the Floyd's triangle number pattern

/**
 * C program to print floyd number pattern
 */

#include <stdio.h>

int main()
{
    int i, j, k, N;

    printf("Enter N: ");
    scanf("%d", &N);

    k = 1;

    for(i=1; i<=N; i++)
    {
        //Logic to print numbers
        for(j=1; j<=i; j++, k++)
        {
            printf("%3d", k);
        }

        printf("\n");
    }

    return 0;
}


Output
Enter N: 5
  1
  2  3
  4  5  6
  7  8  9 10
 11 12 13 14 15


Screenshot

C program to print number pattern


Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment