How to Print Floyds Triangle in C

In this tutorial we will take a quick look at the Floyd’s triangle using the C language. The Floyd’s triangle (named after Robert Floyd) algorithm is a right-angled triangular array of natural numbers. It is defined by filling the rows of the triangle with consecutive numbers, starting with the number one in the top left corner.

This algorithm is often used in programming courses, so it make sense that we take a quick look at it.

Take a look at the following C language source code example of Floyd’s triangle:


#include <stdio.h>

int main() {
	int rows, a,  b, number = 1;
	
	printf("Number of rows of Floyd's triangle to print:");
	scanf("%d",&rows);
	
	for ( a = 1 ; a <= rows ; a++ ) {
		for ( b = 1 ; b <= a ; b++ ) {
			printf("%d ", number);
			number++;
		}
		printf("\n");
	}
	return 0;
}


We start by asking for the numbers of rows we want to print of the Floyd´s triangle. After we have entered a number we start the first for loop (we loop until we have the number of rows). The second for loop that is where we print the numbers, after the print we do number = number + 1. It prints numbers until we are equal to a of the first for loop. We then go to a newline.

Below you’ll find the output of the program, where we have asked to print 8 rows:
Floyds Triangle Output Example

That’s all for this C language tutorial.

This entry was posted in Programming Algorithms. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 10 responses to “How to Print Floyds Triangle in C”

Why not let us know what you think by adding your own comment!

  1. siddhant on September 3rd, 2012:

    thanks

  2. Preeti on September 7th, 2012:

    thanks it is very helpful for me

  3. Kiran on November 1st, 2012:

    Thanks.

  4. appu kumar ims on February 20th, 2013:

    thanks for give n descript…

  5. uzair on April 8th, 2013:

    thanx its very helpful to all.

  6. flora on April 17th, 2013:

    thanks for your support but i would like you to show me the code to display rectangle by using text file.

  7. swetha on June 24th, 2013:

    thanks for introducing a concept which i didn’t know…:)

  8. Dilip on December 11th, 2013:

    Thx

  9. sudhansu, rajkot on February 3rd, 2014:

    Thanks for the concept
    please make many more of this type

  10. hiral rathod on February 16th, 2014:

    what should i do to print this triangle when i m given the last number of last row instead of number of rows….can u help for this?