Observations about the pattern :
- We need to navigate to n number of rows.
- On each row, we need to navigate for numbers same as that of that row number.
- The numbers that are printed go on increasing as they get printed.
/*
* C Program to print Floyd's Triangle.
* 1
* 2 3
* 4 5 6
* 7 8 9 10
*/
// Includes
#include <stdio.h>
// Declarations
/* printFloydTriangle
* Description : Function to print Floyd's triangle.
* Parameters : i_numberOfLines is how many lines triangle to be printed.
* Return : unsigned short 0 - if the triangle was not printed for some reason.
* 1 - if triangle is printed.
*/
unsigned short printFloydTriangle(int i_numberOfLines);
// Difinitions
int main()
{
int i_numberOfLines;
printf("Enter how many lines would you like to print : ");
scanf("%d",&i_numberOfLines);
if (!printFloydTriangle(i_numberOfLines))
{
printf("Could not print the triangle.");
}
}
unsigned short printFloydTriangle(int i_numberOfLines)
{
register unsigned lineItr; // Iterator for number of lines.
register unsigned numberItr; // Iterator for numbers on each line.
register unsigned numberIncrementor; // keeps incrementing as printed.
if (i_numberOfLines <= 0)
{
return 0;
}
// Iterate over each line
for (lineItr = 1, numberIncrementor=1; lineItr <= i_numberOfLines; lineItr++)
{
// On each line - print numbers as much that of current line number
for (numberItr = 1; numberItr <= lineItr; numberItr++)
{
printf("%-5d",numberIncrementor++);
}
// Move on to next line
printf("\n");
}
return 1;
}
No comments:
Post a Comment