Contact Learn C
Copy

Program 34:To Print Floyds Triangle Pattern

Program 34:
 
#include<stdio.h>
main()
{
int rows,i,j,k=1;
printf("Enter number of rows to get Floyds triangle\n");
scanf("%d",&rows);
for(i=1;i<=rows;i++)
{
for(j=1;j<=i;j++)
{
printf("%d ",k);
k++;
}
printf("\n");
}

}
Explanation:
  1. The program starts with initializing
    • rows → Taken from user to print those many rows
    • i,j,k → used as variables.
  2. printf("Enter number of rows to get Floyds triangle\n");
    scanf("%d",&rows);
    Input Taken from user.From out lets take rows=7.
  3. for(i=1;i<=rows;i++)
    {
    This forloop executes rows number of times which means if rows=7 the statements under this for loop will execute 7 times
  4. for(i=1;i<=rows;i++)
    {
       for(j=1;j<=i;j++)
        {
           printf("%d ",k);
           k++;
         }
        printf("\n");
    }
    Let us start Compilation:
    • Iteration 1 of outer forloop: i=1 & i<=7 → true so loop executes
      • Iteration 1 of inner forloop: j=1& 1<=1 → true so loop executes
        • Now it prints value of k which is already initialized to 1
        • Now k is incremented by 1.So k=2.
      • Iteration 2 of inner forloop: j=2& 2<=1 → flase so loop terminates
      • The printed values in this iteration are 1
      • The final values after 1st iteration are i=2,k=2.
      • Then the printf("\n") causes the next iteration to start in new row.
    • Iteration 2 of outer forloop: i=2 & 2<=7 → true so loop executes in new row
      • Iteration 1 of inner forloop: j=1& 1<=2 → true so loop executes
        • Now it prints value of k which is 2
        • Now k is incremented by 1.So k=3
      • Iteration 2 of inner forloop: j=2& 2<=2 → true so loop executes
        • Now it prints value of k which is 3
        • Now k is incremented by 1.So k=4
        • The printed values in this iteration are 2,3
        • The final values after 2nd iteration are i=3,k=4.
        • Then the printf("\n") causes the next iteration to start in new row.
      • Iteration 3 of inner forloop: j=3& 3<=2 → flase so loop terminates
    • In this way the loop goes on until i becomes 7.


 Output:

Print Floyds Triangle Pattern
Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide